Triangle
Solve this ProblemTest Case 1:
Test Case 2:
Test Case 3:
Constraints
- ◆
1 ≤ number of rows in the triangle ≤ 20 - ◆
-1000 ≤ each triangle value ≤ 1000 - ◆
The triangle is passed as a square n×n grid: row i holds i+1 real values followed by unused padding (use 0) out to column n-1
Try the Dry Run
Don't just read the solution — watch it execute, one step at a time.
Approach & Solutions
Brute Force — Recursive Without Memoization
BruteStanding on any position in the triangle, the cheapest total from there down to the bottom edge is that position's own value plus whichever of the two positions directly below it — same column, or one column over — leads to a cheaper finish. Once a position sits on the bottom row, there's nothing left below it, so its cheapest total is simply its own value. Recursing downward from the apex and always taking the cheaper of the two possible next steps finds the minimum path sum, though the same lower position ends up recomputed repeatedly whenever different upper paths funnel into it.
O(2^n)O(n)1class Solution {
2 private int[][] triangle;
3 private int n;
4
5 public int minimumTotal(int[][] triangle) {
6 this.triangle = triangle;
7 this.n = triangle.length;
8 return solve(0, 0);
9 }
10
11 private int solve(int i, int j) {
12 if (i == n - 1) return triangle[i][j];
13 int down = solve(i + 1, j);
14 int diag = solve(i + 1, j + 1);
15 return triangle[i][j] + Math.min(down, diag);
16 }
17}Optimal — Bottom-Up 1D DP
OptimalWork from the bottom row upward. Start by copying the bottom row's own values as the "cheapest finish from here" for each of its positions — there's nothing below them to consider. Then, one row up at a time, replace each position's stored value with its own value plus the cheaper of the two stored values directly below it (same column, or one column over) from the row that was just processed. By the time this sweep reaches the very top row, only one position remains, and it holds the minimum path sum for the whole triangle.
O(n²)O(n)1class Solution {
2 public int minimumTotal(int[][] triangle) {
3 int n = triangle.length;
4 int[] dp = new int[n];
5 for (int j = 0; j < n; j++) dp[j] = triangle[n - 1][j];
6 for (int i = n - 2; i >= 0; i--) {
7 for (int j = 0; j <= i; j++) {
8 dp[j] = triangle[i][j] + Math.min(dp[j], dp[j + 1]);
9 }
10 }
11 return dp[0];
12 }
13}