您的位置:首页 > 其它

LeetCode 120. Triangle

2017-12-18 14:46 316 查看

LeetCode 120. Triangle

问题

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.

分析

我们可以把数值看做路径的长度。

这是一个最短路径问题,DP算法足矣。

但要注意,如果自上而下进行运算会使运算路径发散,从而超时。所以我们采用自下而上的方式。

具体代码实现如下:

class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
while (!triangle.empty())
{
int v_index = triangle.size() - 1;
if (v_index == 0)break;
for (int num_index = 0; num_index < triangle[v_index].size() - 1; num_index++)
{
triangle[v_index - 1][num_index] += min(triangle[v_index][num_index] , triangle[v_index][num_index+1]);
}
triangle.pop_back();
}
return triangle[0][0];
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode