您的位置:首页 > 其它

[LeetCode]62 不同的路径总数

2016-02-28 13:31 495 查看

Unique Paths(不同的路径总数)

【难度:Medium】

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?



位于m*n矩阵的一个机器人只能向下或向右移动,求其从Start移动到Finish不同的走法总数。

解题思路

这是一道典型的动态规划问题,使用一个二维数组ans记忆到达每一点可行的走法总数。首先将左边界点和上边界点初始化为1,因为机器人起始与(0,0),左边界点和上边界点的走法只有1种。接下来的每一点(x,y),可以由(x-1,y)向右走或是(x,y-1)向下走来到达,因此在(x,y)这一点可到达的方法有ans[x-1][y]+ans[x][y-1]种,到达终点的方法则是ans最后一个点的数据。

c++代码如下

class Solution {
public:
int uniquePaths(int m, int n) {
if (m == 0 || n == 0) {
return 0;
}
vector<vector<int>> path(m,vector<int>(n,0));
for (int i = 0; i < m; i++)
path[i][0] = 1;
for (int i = 0; i < n; i++)
path[0][i] = 1;
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
path[i][j] = path[i-1][j] + path[i][j-1];
}
}
return path[m-1][n-1];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: