您的位置:首页 > 其它

120. Triangle(Array; DP, WPS)

2015-10-27 20:10 309 查看
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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: