码迷,mamicode.com
首页 > 其他好文 > 详细

Lintcode: Unique Paths

时间:2015-11-30 12:57:25      阅读:107      评论:0      收藏:0      [点我收藏+]

标签:

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 };

 

Lintcode: Unique Paths

标签:

原文地址:http://www.cnblogs.com/CheeseZH/p/5006718.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!