Triangle
Pattern: 2D grid DP
Work from the bottom row up: each cell's best path to the bottom is its value plus the smaller of the two cells below it. The top cell then holds the answer.
The problem
Given a triangle of numbers, return the smallest sum of a path from the top to the bottom, moving to one of the two adjacent numbers in the row below each time.
Think first
- Is it easier to go top-down or bottom-up?
- From cell (r, c), where can you go?
- Where is the answer?
Hints
Brute force, and why it fails
Try every path: 2ⁿ.
The key insight
Bottom-up, each cell needs only the row below, and the answer is the single top cell.
Dry run
| best | 4 1 8 3 |
|---|
[[2], [3, 4], [6, 5, 7], [4, 1, 8, 3]]. Start from the bottom: 4 1 8 3.
Step 1 of 3
The plan
best = bottom row
for rows upwards: best[c] = row[c] + min(best[c], best[c + 1])
return best[0]
Complexity
- Time
O(n²)- Space
O(n)
Each number once.
Edge cases
- One row.
- Negative numbers.
- All equal.
I've built my logic, show the code
Java
class Solution {
public int minimumTotal(int[][] triangle) {
int n = triangle.length;
int[] best = triangle[n - 1].clone(); // start from the bottom row
for (int r = n - 2; r >= 0; r--)
for (int c = 0; c <= r; c++) best[c] = triangle[r][c] + Math.min(best[c], best[c + 1]); // the better of the two below
return best[0];
}
}C++
class Solution {
public:
int minimumTotal(vector<vector<int>>& triangle) {
int n = static_cast<int>(triangle.size());
vector<int> best(triangle[n - 1]); // start from the bottom row
for (int r = n - 2; r >= 0; r--)
for (int c = 0; c <= r; c++) best[c] = triangle[r][c] + min(best[c], best[c + 1]); // the better of the two below
return best[0];
}
};Python
class Solution:
def minimumTotal(self, triangle: list[list[int]]) -> int:
best = list(triangle[-1]) # start from the bottom row
for row in reversed(triangle[:-1]):
best = [v + min(best[c], best[c + 1]) for c, v in enumerate(row)] # the better of the two below
return best[0]Common mistakes
- Going top-down and forgetting to take the minimum at the end.
- Using the wrong neighbours.