Triangle
iven 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.
分析:可以將問題分解考慮,從低至頂的分析方法。
設狀態f[i][j],表示點(i,j)到頂部的距離,則f[i][j]=min(f[i-1][j-1],f[i-1][j])+(i,j),當然最左和最右端的計算方式稍有變化。最後找出最小值即可。
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
int n=triangle.size();
vector<int> f(n);
f[0]=triangle[0][0];
for(int i=1;i<n;i++){
for(int j=triangle[i].size()-1;j>=0;j--){
int mn;
if(j==0){
mn=f[j];
}
if(j==i){
mn=f[j-1];
}
else{
mn=min(f[j-1],f[j]);
}
f[j]=mn+triangle[i][j];
}
}
int min_sum=f[0];
for(int i=1;i<n;i++)
if(min_sum>f[i])min_sum=f[i];
return min_sum;
}
};