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题,状态转移公式为:
f[i][j] = (a[i][j] +min(f[i-1][j],f[i-1][j-1]) i>0&&j<i
f[i][j] = (a[i][j] + f[i-1][j]) i==0
f[i][j] = (a[i][j] + f[i-1][j-1]) i==j
由于需要O(n)的空间复杂度,其实我们只需要定义两个长度为n的数组,分别为f,pre,f表示当前行的各个数最小和,pre表示上一行各个数最小和。即可满足要求。
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
int i,j;
if(triangle.empty()) {
return 0;
}
int Min = INT_MAX;
vector<int> f;
vector<int> pre;
f.resize(triangle[triangle.size()-1].size());
pre.resize(triangle[triangle.size()-1].size());
for(i=0; i<triangle.size(); ++i) {
f.clear();
for(j=0; j<triangle[i].size(); ++j) {
f[j] = triangle[i][j];
if(i>0) {
if(j<1) {
f[j] += pre[j];
}
else if(j<i){
f[j] += (pre[j-1]<=pre[j]?pre[j-1]:pre[j]);
}
else {
f[j] += pre[j-1];
}
}
if (i==triangle.size()-1) {
Min = (Min<f[j] ? Min:f[j]);
}
}
pre.clear();
for(j=0; j<triangle[i].size(); ++j) {
pre[j] = f[j];
}
}
return Min;
}
};