题目描述:
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?
Notice
m and n will be at most 100.
Example
题目思路:
1,1 | 1,2 | 1,3 | 1,4 | 1,5 | 1,6 | 1,7 |
2,1 | | | | | | |
3,1 | | | | | | 3,7 |
Above is a 3 x 7 grid. How many possible unique paths are there?
一道简单的dp题,从题目要求:当前的点只能来自上面和左边,那么到达当前点的路径数 = 到达上面点的路径数+到达左边点的路径数。这样就得到了dp方程。
Mycode (AC = 71ms):
class Solution {
public:
/**
* @param n, m: positive integer (1 <= n ,m <= 100)
* @return an integer
*/
int uniquePaths(int m, int n) {
// wirte your code here
vector<vector<int>> paths(100, vector<int>(100, 1));
// The number of paths at (i, j) is
// the addition from upper and left
for(int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
paths[i][j] = paths[i - 1][j] + paths[i][j - 1];
}
}
return paths[m - 1][n - 1];
}
};