Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
int minimumTotal(vector<vector<int>>& triangle) { // time: O(n^2); space: O(n^2)
int n = triangle.size();
vector<vector<int> > sum(n, vector<int>(n, 0));
for (int i = n - 1; i >= 0; --i) {
for (int j = i; j >= 0; --j) {
sum[i][j] = (i == n - 1 ? 0 : min(sum[i + 1][j], sum[i + 1][j + 1])) + triangle[i][j];
// cout << "i: " << i << ", j: " << j << ", sum[i][i]: " << sum[i][j] << endl;
}
}
return sum.front().front();
}
// Space optimized dynamic programming
int minimumTotal(vector<vector<int>>& triangle) { // time: O(n^2); space: O(n)
int n = triangle.size();
vector<int> sum(n, 0);
for (int i = n - 1; i >= 0; --i) {
int bottomRight = i == n - 1 ? 0 : sum[i + 1];
for (int j = i; j >= 0; --j) {
int bottom = sum[j];
sum[j] = min(sum[j], bottomRight) + triangle[i][j];
bottomRight = bottom;
}
}
return sum.front();
}