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).
Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
思路:与119题类似,只是现在DP中存储的不是数组的值,而是到目前为止的minimum sum。赋值DP时为了避免改变上一行结果,也是得从右往左
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.empty()) return ; int minValue = INT_MAX;
vector<int> dp(triangle.size());
dp[]=triangle[][];
for(int i = ; i < dp.size(); i++){
dp[i] = dp[i-]+triangle[i][i];
for(int j = i-; j > ; j--){
dp[j] = min(dp[j-],dp[j])+triangle[i][j];
}
dp[] += triangle[i][];
} for(int i = ; i < dp.size(); i++){
if(dp[i] < minValue){
minValue = dp[i];
}
} return minValue;
}
};