您的位置:首页 > 其它

leetcode_120. Triangle

2017-04-30 11:27 232 查看
题目:

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).
动态规划问题。从下到上,每个数的最短路径都是到下面两个数的最短路径+这个数。即min(minm[i], minm[i+1])+triangle[row][i];
从下到上,第一层得到的就是到第2层的最短路的最小值加第一层的数。

代码如下:

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