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. Follow Up

Could you do this using only O(n) extra space, where n is the total number of rows in the triangle?

5. Solutions

Dynamic Programming - Down to Top(Follow Up)

n is the number of nodes in the triangle
Time complexity: O($n^2$)
Space complexity: O(n)

class Solution {
public:
    int minimumTotal(const vector<vector<int>> &triangle) {
        int min_sum = triangle[0][0];
        auto dp = triangle[0]; // dp[i] means current level i-th value min sum
        for (int i = 1; i < triangle.size(); ++i) {
            dp.push_back(triangle[i].back() + dp.back());
            min_sum = dp.back();
            for (int j = dp.size() - 2; j > 0; --j) {
                dp[j] = triangle[i][j] + min(dp[j], dp[j - 1]);
                min_sum = min(dp[j], min_sum);
            }

            dp[0] += triangle[i][0];
            min_sum = min(dp[0], min_sum);
        }

        return min_sum;
    }
};
comments powered by Disqus