120. Triangle
1. Description
Given a triangle array, return the minimum path sum from top to bottom.
For each step, you may move to an adjacent number of the row below. More formally, if you are on index i on the current row, you may move to either index i or index i + 1 on the next row.
2. Example
Example 1
Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
Output: 11
Example 2
Input: triangle = [[-10]]
Output: -10
3. Constraints
- 1 <= triangle.length <= 200
- triangle[0].length == 1
- triangle[i].length == triangle[i - 1].length + 1
- -$10^4$ <= triangle[i][j] <= $10^4$
4. Solutions
Dynamic Programming (Bottom to Up)
n = triangle.size()
Time complexity: O($n^2$)
Space complexity: O(n)
class Solution {
public:
int minimumTotal(const vector<vector<int>> &triangle) {
const int m = triangle.size(), n = triangle.back().size();
vector<int> min_sum_end_at = triangle.back();
for (int i = m - 2; i >= 0; --i) {
for (int j = 0; j <= i; ++j) {
min_sum_end_at[j] = triangle[i][j] + min(min_sum_end_at[j], min_sum_end_at[j + 1]);
}
}
return min_sum_end_at.front();
}
};