题目:
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.
代码:
class Solution { public: int uniquePaths(int m, int n) { int dp[m][n]; memset(dp, 0, sizeof(dp)); for ( size_t i = 0; i < n; ++i ) dp[0][i] = 1; for ( size_t i = 0; i < m; ++i ) dp[i][0] = 1; for ( size_t i = 1; i < m; ++i ) { for ( size_t j = 1; j < n; ++j ) { dp[i][j] = dp[i-1][j] + dp[i][j-1]; } } return dp[m-1][n-1]; } };
tips:
常规dp解法。
=====================================
上面的代码有可以改进的地方:dp[m][n]并不用这些额外空间,只需要两个长度为n的数组即可;一个保存前一行的状态,一个用于遍历当前行的状态,每次滚动更新,可以省去额外空间。沿着上述思路改进了一版代码如下:
class Solution { public: int uniquePaths(int m, int n) { int curr[n], pre[n]; for ( size_t i = 0; i<n; ++i ) { pre[i]=1; curr[i]=0; } curr[0] = 1; for ( size_t i = 1; i<m; ++i ) { for ( size_t j = 1; j<n; ++j ) { curr[j] = curr[j-1] + pre[j]; pre[j] = curr[j]; } curr[0] = 1; } return pre[n-1]; } };
这个代码空间复杂度降到了O(n),但还是可以改进。其实只用一个一维的数组dp就可以了,代码如下。
class Solution { public: int uniquePaths(int m, int n) { int curr[n]; memset(curr, 0, sizeof(curr)); curr[0] = 1; for ( size_t i = 0; i < m; ++i ) { for ( size_t j = 1; j < n; ++j ) { curr[j] = curr[j-1] + curr[j]; } } return curr[n-1]; } };
这里用到了滚动数组的技巧。有个细节需要注意,外层dp是可以从0行开始,省去了一部分代码。
时间: 2024-11-02 19:41:44