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

[leetcode] 62. Unique Paths

2016-01-26 15:36 417 查看
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.

这道题是机器人想从左上角走到右下角,问可能的路径数,题目难度为Medium。

在任一位置,机器人有两个选择,向下或向右,把向下和向右两个位置所有可能的路径相加即得到了此位置到右下角所有可能的路径数。一道比较典型的动态规划题目,具体代码:
class Solution {
public:
int uniquePaths(int m, int n) {
if(m < 1 && n < 1) return 0;
vector<vector<int>> rst(m, vector<int>(n, 0));

for(int i=0; i<m; i++) rst[i][n-1] = 1;
for(int i=0; i<n; i++) rst[m-1][i] = 1;

for(int i=m-2; i>=0; i--) {
for(int j=n-2; j>=0; j--) {
rst[i][j] = rst[i+1][j] + rst[i][j+1];
}
}

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