空間O(N^2)
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
for(int i = triangle.size()-2; i >= 0; --i)
for(int j = 0; j <= i; j++)
triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]);
return triangle[0][0];
}
};
空間優化爲O(N)
class Solution {
public:
int minimumTotal(vector<vector<int> > &triangle) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(triangle.empty()) return 0;
vector<int> f(triangle.back());
for(int i = triangle.size() - 2; i >= 0; i--)
for(int j = 0; j <= i; j++)
f[j] = min(f[j], f[j+1]) + triangle[i][j];
return f[0];
}
};