Unique Paths
Total Accepted: 36748 Total Submissions: 112531My SubmissionsA 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.
Array Dynamic Programming思路一: 动态规划, f[i][j] = f[i-1][j] + f[i][j-1], 且f[i][0] = 0, f[0][j]=0, f[1][1] =1 ,时间复杂度O(m*n),空间复杂度O(m*n)
class Solution { public: int uniquePaths(int m, int n) { vector<int> row(n + 1, 0); vector<vector<int> > f(m + 1, row); f[1][1] = 1; for(int i = 1; i <= m; i ++) { for(int j = 1; j <= n; j ++) { if(i == 1 && j == 1) continue; f[i][j] = f[i-1][j] + f[i][j-1]; } } return f[m][n]; } };
思路二:空间复杂度还可以优化,将f[][] 改成 f[],优化后,时间复杂度不变,空间复杂度O(n)
class Solution { public: #if 0 int uniquePaths(int m, int n) { vector<int> row(n + 1, 0); vector<vector<int> > f(m + 1, row); f[1][1] = 1; for(int i = 1; i <= m; i ++) { for(int j = 1; j <= n; j ++) { if(i == 1 && j == 1) continue; f[i][j] = f[i-1][j] + f[i][j-1]; } } return f[m][n]; } #endif int uniquePaths(int m, int n) { vector<int> f(n + 1, 0); f[1] = 1; for(int i = 1; i <= m; i ++) { for(int j = 1; j <= n; j ++) { if(i == 1 && j == 1) continue; f[j] = f[j] + f[j-1]; } } return f[n]; } };