zoukankan      html  css  js  c++  java
  • LeetCode 62. Unique Paths(所有不同的路径)

    A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

    The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

    How many possible unique paths are there?

    Above is a 3 x 7 grid. How many possible unique paths are there?

    Note: m and n will be at most 100.


    题目标签:Array

      这道题目给了我们一个matrix 的m 和n, 让我们从[0,0] 开始,找到所有不同的路径到[m-1][n-1]。我们可以来看一个比原题简单一点的例子:

      3 * 3 matrix,我们设起点为1。每一个点代表的是,走到这个点的不同路径的数量

           1  0  0

           0  0  0

           0  0  0

      我们可以发现,机器人只能往右和下走,所以路径的可能只能来自于左和上。

      所以我们可以遍历matrix,把这个点的左边点,和上面点加起来,就等于到这个点的路径之和。

      1  1  1

      1  2  3

      1  3  6

      最后一个点,[m-1][n-1]就是所有不同路径的总数。

     

    Java Solution:

    Runtime beats 5.14% 

    完成日期:07/20/2017

    关键词:Array

    关键点:Dynamic Programming, 逆向思考

     1 public class Solution 
     2 {
     3     public int uniquePaths(int m, int n) 
     4     {
     5         int[][] matrix = new int[m][n];
     6         
     7         matrix[0][0] = 1; // start point
     8         
     9         for(int i=0; i<m; i++) // row
    10         {
    11             for(int j=0; j<n; j++) // column
    12             {
    13                 // get left
    14                 if(j-1 >=0)
    15                     matrix[i][j] += matrix[i][j-1];
    16                 // get top
    17                 if(i-1 >=0)
    18                     matrix[i][j] += matrix[i-1][j];
    19             }
    20         }
    21         
    22         return matrix[m-1][n-1];
    23     }
    24 }

    参考资料:

    http://www.cnblogs.com/grandyang/p/4353555.html

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    使用URLEncoder、URLDecoder进行URL参数的转码与解码
    js中的连等==和全等===
    sass用法
    sass/scss 和 less的区别
    JSON与localStorage的爱恨情仇
    ionic2
    雪碧图
    JavaScript交换两个变量值的七种解决方案
    JavaScript中的[]和{}
    为什么 ++[[]][+[]]+[+[]] = 10?
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7215733.html
Copyright © 2011-2022 走看看