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.
方法1:从上向下进行遍历dp,但是这样写的代码比较繁琐。
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.size() == 0||triangle[0].size()==0)
return 0 ;
int* buffer = new int[triangle[triangle.size() - 1].size()];
buffer[0] = triangle[0][0];
for(int row = 1 ; row < triangle.size(); ++row){
for(int col = triangle[row].size() - 1; col >= 0; --col){
if(col == triangle[row].size() - 1){
buffer[col] = buffer[col - 1]+ triangle[row][col];
}
else if(col == 0){
buffer[col] = buffer[col] + triangle[row][col];
}
else{
buffer[col] = min(buffer[col-1],buffer[col]) + triangle[row][col];
}
}
}
int sum = INT_MAX;
for(int i = 0 ; i < triangle[triangle.size() - 1].size(); ++i){
if(sum > buffer[i])
sum = buffer[i];
}
return sum;
}
};
方法2:从下向上进行遍历dp,这样的代码相对从上到下而言比较简洁。
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.size() == 0)
return 0;
vector<int> res = triangle[triangle.size()-1];
for(int row = triangle.size() - 2; row >=0; --row){
for(int col = 0; col < triangle[row].size(); ++col){
res[col] = triangle[row][col]+min(res[col],res[col+1]);
}
}
return res[0];
}
};