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).
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
这道题首先想到的解决思路是DFS,用一个cursum临时变量记录每一条路径
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.empty())
return 0;
int sum=INT_MAX;
int cursum=0;
mincore(triangle,sum,cursum,0,0);
return sum;
}
void mincore(vector<vector<int>>& v,int& sum,int cursum,int r,int c){
if(r==v.size()){
sum=min(sum,cursum);
return ;
}
cursum+=v[r][c];
mincore(v,sum,cursum,r+1,c);
mincore(v,sum,cursum,r+1,c+1);
}
无奈复杂度过高,只能另辟蹊径。把递归转换成迭代。在网上找了一个从下往上迭代的思路:
int minimumTotal(vector<vector<int>>& triangle) {
if(triangle.empty())
return 0;
for(int i=triangle.size()-2;i>=0;--i){
for(int j=0;j<triangle[i].size();++j){
triangle[i][j]+=triangle[i+1][j]<triangle[i+1][j+1]?triangle[i+1][j]:triangle[i+1][j+1];
}
}
return triangle[0][0];
}
这个思路寥寥几句,着实厉害!!