描述
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?
从左上角开始,每次只能向右以及向下,问到右下角一共有多少种走法。
分析
典型的动态规划的题目,设 dp[i][j] 表示从起点到点 (i,j) 的路线数目,那么递推公式很明显:
dp[i][j]=dp[i−1][j]+dp[i][j−1]
为了减小空间复杂度可以将
dp
每一列进行共用,代码如下。
代码
class Solution {
public:
int uniquePaths(int m, int n) {
vector<int> dp(n, 1);
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
dp[j] += dp[j - 1];
}
}
return dp[n - 1];
}
};