C++
dp
递推式:dp[i][j] = dp[i-1][j] + dp[i][j-1]
初值:dp[i][j] = 1,i=0 or j=0
空间优化:省掉一维
1 class Solution { 2 public: 3 /** 4 * @param n, m: positive integer (1 <= n ,m <= 100) 5 * @return an integer 6 */ 7 int uniquePaths(int m, int n) { 8 // wirte your code here 9 vector<vector<int> > dp(m,vector<int>(n)); 10 for (int i = 0; i < m ; ++i) { 11 for (int j = 0; j < n; ++j) { 12 if ( i == 0 ) { 13 dp[i][j] = 1; 14 } else if ( j == 0 ) { 15 dp[i][j] = 1; 16 } else { 17 dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; 18 } 19 } 20 } 21 return dp[m - 1][n - 1]; 22 } 23 };
空间优化
1 class Solution { 2 public: 3 /** 4 * @param n, m: positive integer (1 <= n ,m <= 100) 5 * @return an integer 6 */ 7 int uniquePaths(int m, int n) { 8 // wirte your code here 9 // vector<vector<int> > dp(m,vector<int>(n)); 10 vector<int> dp(n); 11 for (int i = 0; i < m ; ++i) { 12 for (int j = 0; j < n; ++j) { 13 if ( i == 0 ) { 14 dp[j] = 1; 15 } else if ( j == 0 ) { 16 dp[j] = 1; 17 } else { 18 dp[j] = dp[j] + dp[j - 1]; 19 } 20 } 21 } 22 return dp[n - 1]; 23 } 24 };
本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/p/5006718.html,如需转载请自行联系原作者