您的位置:首页 > 编程语言 > C语言/C++

LeetCode - 120. Triangle - 思路详解 - C++

2017-01-17 23:18 387 查看

题目

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).

翻译

假设有个三角形。找出从顶部到底部的最小路径。每一步你可以移动到下层的相邻的位置。

举例下图,假设有三角形。

最小的路径为11,【2+3+5+1 = 11】

思路

要求最小路径。我们首先分析,走到第i层,必然从第i-1层到来。即要求最小值,可以用公式

min( a[i-1][j]+a[i][j],a[i-1][j] + a[j][j+1] ) (0 <= j < n;n 位第i层的数的个数;i表示层数)。

其实这里可以看出这是一道典型的动态规划的问题。

代码

class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = triangle.size();
//用来存储计算中间结果
vector<int> buf(n,0);
int res = 0;
for(int i = n-1;  i> 0; i-- ){
for(int j = 0; j < i; j ++){
buf[j] = min(triangle[i][j],triangle[i][j+1]);
}

for(int j = 0; j < i; j++){
triangle[i-1][j] += buf[j];
}
}

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