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.
//f(i,j) = min (f(i+1,j),f(i+1,j+1)) +a[i][j] ---->自底向上
从底端与之比较的为累加值,与相邻的元素值,在于它比较!!
//f(i,j) = min (f(i+1,j),f(i+1,j+1)) +a[i][j] ---->自底向上
int minimumTotal(vector<vector<int> > &triangle) {
int row = triangle.size();
for(int i = row-2 ;i >=0; i--)//第一行开始
{
for(int j = 0 ; j <= i ;j++ )
{
triangle[i][j] = min(triangle[i+1][j],triangle[i+1][j+1]) + triangle[i][j];//被覆盖!
}
}
return triangle[0][0];
}
//自顶向下的方式。(稍微麻烦点,因为要考虑俩短情况)以下f[][]可以用一维数组改进。
int minimumTotal(vector<vector<int> > &triangle) {
int row = triangle.size();
int f[row][triangle[row-1].size()];
int val1,val2;
int min_val = INT_MAX;
f[0][0]=triangle[0][0];
for(int i=1;i<row;i++)
{
f[i][i+1] = INT_MAX;
for(int j=0;j<=i;j++)
{
val1 = j>=1?f[i-1][j-1]:INT_MAX;
val2 = j<i? f[i-1][j]:INT_MAX;
f[i][j]=min(val1,val2)+triangle[i][j];
}
}
for(int i=0;i<row;i++)
{
min_val = min(f[row-1][i],min_val);
}
return min_val;
}