[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).
题意:求从top走到buttom的路径上数字之和的最小值。走法:只能走下一行隔壁的两个数字。
分析:只能走下一行隔壁的两个数字,即 triangle[row][col] 只能走到 triangle[row+1][col]或者triangle[row+1][col+1]
利用ans[row][col]表示从triangle[row][col]出发的最小和
从走法我们可以得出ans[row][col] = triangle[row][col] + min(ans[row+1][col], ans[row+1][col+1])
上面这个就是状态转移方程
从方程可以看出,要得到第row层的答案,要先计算出row+1层的结果,所以要从buttom出发。
代码:(Runtime: 5 ms)
static string x = [](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return "";
}();
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
vector<int>& ans = triangle.back();
for(int i = triangle.size() - 2; i >= 0; --i){
for(int j = 0; j <= i; ++j)
ans[j] = min(ans[j], ans[j+1]) + triangle[i][j];
}
return ans[0];
}
};
9494



被折叠的 条评论
为什么被折叠?



