您的位置:首页 > 产品设计 > UI/UE

LeetCode 62. Unique Paths(所有不同的路径)

2017-07-21 06:35 387 查看

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, 逆向思考

 

public class Solution
{
public int uniquePaths(int m, int n)
{
int[][] matrix = new int[m]
;

matrix[0][0] = 1; // start point

for(int i=0; i<m; i++) // row
{
for(int j=0; j<n; j++) // column
{
// get left
if(j-1 >=0)
matrix[i][j] += matrix[i][j-1];
// get top
if(i-1 >=0)
matrix[i][j] += matrix[i-1][j];
}
}

return matrix[m-1][n-1];
}
}

参考资料:

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

 

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

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: