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).
给出一个三角,从顶到底最小的路程。每次只能走相邻的数值,每行只能走一次。求最小值。
其实倒着走更好一点,这样每个值都有两个路可选,从上往下的话边界和中间数目的走路条件不一样,
从下往上走,每一个都是下面两个的最小值加上triangle的值。
minpath[k][i]=triangle[k][i]+min(minpath[k+1][i+1],minpath[k+1][i]);
可以简化掉:
minpath[i] = min( minpath[i], minpath[i+1]) + triangle[k][i];
在minpath还没走到第k行时其中存储的就是k+1行的,一旦走到了更替掉的就不会再用到。
这样循环即可。
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
vector<int> dp= triangle[triangle.size()-1];
for(int i=triangle.size()-2;i>=0;--i){
for(int j=0;j<triangle[i].size();++j){
dp[j]=triangle[i][j]+min(dp[j],dp[j+1]);
}
}
return dp[0];
}
};