您的位置:首页 > 其它

算法作业_27(2017.6.8第十六周)

2017-06-08 18:39 197 查看
120. Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjachttp://write.blog.csdn.net/posteditent 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).

解析:动态规划的题目,求一个三角形二维数组从顶端到地段的最小路径。我们可以从底端(倒数第二行)开始,采用又底向上的方法。

状态转移方程为:dp[i][j] = min(dp[i+1][j] + dp[i+1][j+1]) +dp[i][j]。dp[0][0]就是答案,代码如下:

class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int size = triangle.size();
for(int i = size-2;i>=0;i--){

for(int j = 0;j<=i;j++){
triangle[i][j] = min(triangle[i+1][j],triangle[i+1][j+1])+triangle[i][j];
}
}
return triangle[0][0];
}
};

 

Add to List


120. Triangle

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