首页 > 其他 > 详细

120. Triangle(Array; DP)

时间:2015-10-27 21:55:10      阅读:274      评论:0      收藏:0      [点我收藏+]

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

 

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        vector<int> dp;
        int height = triangle.size();
        int i,j,minSum;
        
        dp.push_back(triangle[0][0]);
        for(i = 1; i < height; i++){
            dp[0]=dp[0]+triangle[i][0];
            for(j = 1; j < triangle[i].size()-1; j++){
                dp[j] = min(dp[j-1],dp[j])+triangle[i][j]; //有问题,下一个循环的时候dp[j-1]被改变了
            }
            dp.push_back(dp[j-1]+triangle[i][j]);
        }
        
        minSum = dp[0];
        for(int i = 1; i<triangle[height-1].size(); i++)
        {
            if(dp[i] < minSum)
                minSum = dp[i];
        }
        return minSum;
    }
};

Result: Wrong Answer

Input:
[[-1],[-2,-3]]
Output:
-6
Expected:
-4

所以要从右往左改变dp: 

class Solution {
public:
    int minimumTotal(vector<vector<int>>& triangle) {
        vector<int> dp;
        int height = triangle.size();
        int i,j,minSum;
        
        dp.push_back(triangle[0][0]);
        for(i = 1; i < height; i++){
            dp.push_back(dp[triangle[i-1].size()-1]+triangle[i][triangle[i].size()-1]);
            for(j = triangle[i].size()-2; j >= 1; j--){
                dp[j] = min(dp[j-1],dp[j])+triangle[i][j];
            }
            dp[0]=dp[0]+triangle[i][0];
        }
        
        minSum = dp[0];
        for(int i = 1; i<triangle[height-1].size(); i++)
        {
            if(dp[i] < minSum)
                minSum = dp[i];
        }
        return minSum;
    }
};

 

120. Triangle(Array; DP)

原文:http://www.cnblogs.com/qionglouyuyu/p/4915386.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!