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 is11(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.
通过这种方式,可以得到从第一行到第n行的所有点的最小和值,然后
取第n行的最小值即可[cpp] view plain copy
class Solution
{
public:
int minimumTotal(vector<vector<int>> & triangle)
{
if (triangle.size()==0)
{
return 0;
}
vector<vector<int>> dp;
vector<int> vec;
vec.push_back(triangle[0][0]);
dp.push_back(vec);
vec.resize(0);
for (int i=1; i<triangle.size(); i++)
{
for (int j=0; j<triangle[i].size(); j++)
{
if (j==0)
{
vec.push_back(triangle[i][0]);
}
else if(j==triangle[i].size()-1)
{
vec.push_back(triangle[i][j]+dp[i-1][j-1]);
}
else
{
vec.push_back(min(dp[i - 1][j - 1] + triangle[i][j], dp[i - 1][j] + triangle[i][j]));
}
}
dp.push_back(vec);
vec.resize(0);
}
int last = dp.size() - 1;
int minpath = dp[last][0];
for (int i = 1; i<dp[last].size(); i++)
if (dp[last][i]<minpath)
minpath = dp[last][i];
return minpath;
}
};