您的位置:首页 > 其它

Triangle

2015-08-04 20:20 246 查看
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.

Solution:

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

return minsum;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: