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.
跟矩阵从左上到右下有多少种走法,以及最小和路径是一样的,朴素的DP需要O(n2)的空间,我们先写一个,其实如果要求O(n)的空间无非就是用滚动数组,也不难的。
#define vvi vector<vector<int> >
class Solution {
public:
int minimumTotal(vvi& tri)
{
vvi dp(tri);
int n=tri.size();
int i,j;
for(i=1;i<n;i++)
{
int m=tri[i].size();
dp[i][0]+=dp[i-1][0];
for(j=1;j<m-1;j++)
dp[i][j]=min(dp[i-1][j-1],dp[i-1][j])+tri[i][j];
dp[i][m-1]+=dp[i-1][m-2];
}
return *min_element(dp[n-1].begin(),dp[n-1].end());
}
};
下面是用滚动数组的:
#define vvi vector<vector<int> >
class Solution {
public:
int minimumTotal(vvi& tri)
{
int n=tri.size();
if ( n==0 )
return 0;
vector<int> dp(1,tri[0][0]);
int i,j;
for(i=1;i<n;i++)
{
int m=tri[i-1].size();
dp.push_back(dp[m-1]+tri[i][m]);
for(j=m-1;j>0;j--)
dp[j]=min(dp[j-1],dp[j])+tri[i][j];
dp[0]+=tri[i][0];
}
return *min_element(dp.begin(),dp.end());
}
};