题目描述:
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, wheren is the total number of rows in the triangle.
每个点只可以经过正下方和右下方的点到达最后一层,选取其中的较小的路径和加上该点本身的值,得到该点的最小路径和,然后依次算出最后一层每个点的最小路径和,再求它们的最小值。
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle)
{
int n=triangle.size();
int v[n][n];
v[0][0]=triangle[0][0];
for(int i=1;i<n;i++)
{
for(int j=0;j<=i;j++)
{
if(j==0) v[i][j]=v[i-1][j]+triangle[i][j];
else if(i==j) v[i][j]=v[i-1][j-1]+triangle[i][j];
else v[i][j]=min(v[i-1][j],v[i-1][j-1])+triangle[i][j];
}
}
int min=0xFFFF;
for(int i=0;i<n;i++)
{
if(min>=v[n-1][i]) min=v[n-1][i];
}
return min;
}
};