题意:计算一个三角形从上到下的路径和的最小值。
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).
代码:
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n=triangle.size();
if(n==0) return 0;
vector<vector<int> >dp(2,vector<int>(n));
dp[0][0]=triangle[0][0];
int cur=1,pre=0;
for(int i=1;i<n;i++)
{
for(int j=0;j<triangle[i].size();j++)
{
int l,r;
if(j-1<0) dp[cur][j]=triangle[i][j]+dp[pre][j];
else if(j>=i) dp[cur][j]=triangle[i][j]+dp[pre][j-1];
else dp[cur][j]=triangle[i][j]+min(dp[pre][j],dp[pre][j-1]);
}
pre=cur;cur=(cur+1)%2;
}
int minn=999999999;
for(int i=0;i<n;i++)
{
if(dp[pre][i]<minn) minn=dp[pre][i];
}
return minn;
}
};