Difficulty: Medium
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]表示从(0,0)走到(i,j)的最小和
状态转移方程:
f[i][0]=f[i-1][0]+triangle[i][0]
f[i][j]=min(f[i-1],[j-1],f[i-1][j]) + triangle[i][j]
f[i][i]=f[i-1][i-1] + triangle[i][i]
时间复杂度O(n * n)
实现O(n) extra space只需要用滚动数组就可以了,见代码
class Solution {
public:
int minimumTotal(vector<vector<int> >& triangle) {
int i,j,k,n;
n=triangle.size();
vector<int> f[2];
f[0].resize(n);
f[1].resize(n);
f[0][0]=triangle[0][0];
for(i=k=1;i<n;i++,k=1-k)
{
f[k][0]=f[1-k][0] + triangle[i][0];
f[k][i]=f[1-k][i-1] + triangle[i][i];
for(j=1;j<i;j++)
f[k][j]=min(f[1-k][j-1],f[1-k][j])+triangle[i][j];
}
int res=f[1-k][0];
for(i=1;i<n;i++)
res=min(res,f[1-k][i]);
return res;
}
};