Triangle

Minimum top-to-bottom path sum in a triangle — in-place bottom-up DP.

Medium
Time O(n^2) Space O(1)
LeetCode
2 min read
dp

Problem#

Minimum path sum from top to bottom of a triangle. Each step moves to one of the two adjacent cells of the next row.

Examples#

  • [[2],[3,4],[6,5,7],[4,1,8,3]]11

Constraints#

  • 1 <= n <= 200.

Approach#

Bottom-up: triangle[i][j] += min(triangle[i+1][j], triangle[i+1][j+1]). Top of the modified triangle holds the answer.

Solution#

Triangle
class Solution {
public:
int minimumTotal(vector<vector<int>>& t) {
for (int i = t.size() - 2; i >= 0; --i)
for (int j = 0; j <= i; ++j)
t[i][j] += min(t[i + 1][j], t[i + 1][j + 1]);
return t[0][0];
}
};

Editorial#

In-place bottom-up avoids any extra storage. Going bottom-up sidesteps the “I don’t know future minimums” problem of top-down — every cell’s children are already finalized.

Complexity#

  • Time: O(n²).
  • Space: O(1).

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.