[Leetcode] Unique Paths
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.
见代码。
1 class Solution { 2 public: 3 int uniquePaths(int m, int n) { 4 int a[m][n]; 5 for (int i = 0; i < n; ++i) { 6 a[0][i] = 1; 7 } 8 for (int i = 0; i < m; ++i) { 9 a[i][0] = 1; 10 } 11 for (int i = 1; i < m; ++i) { 12 for (int j = 1; j < n; ++j) { 13 a[i][j] = a[i-1][j] + a[i][j-1]; 14 } 15 } 16 return a[m-1][n-1]; 17 } 18 };
第二遍做的时候果然有新收获,感觉Leetcode刷再多遍都不嫌多,每一次都会有新的收获。下面为第二次刷的时候的代码,我们完全用不着m*n的空间,其实只要m跟n相对较短的那个长度的空间就好了。下面是用了O(n)空间的代码。
1 class Solution { 2 public: 3 int uniquePaths(int m, int n) { 4 if (m == 0 || n == 0) return 0; 5 vector<int> dp(n, 1); 6 for (int i = 1; i < m; ++i) { 7 for (int j = 1; j < n; ++j) { 8 dp[j] += dp[j-1]; 9 } 10 } 11 return dp[n-1]; 12 } 13 };