sagelearnai

Triangle

Difficulty: Medium · Pattern: 2-D Dynamic Programming · LeetCode #120

Return the minimum path sum from the top of the triangle to the bottom. From index j in one row, you may move to index j or j + 1 in the next row.

Example

text
   2
  3 4
 6 5 7
4 1 8 3     →  11   (2 + 3 + 5 + 1)

Hints

  1. Going top-down, every path ends somewhere on the bottom row and you take a min at the end. Going bottom-up collapses everything into the top cell.

Approach

Start with dp = last row. For each row going up: dp[j] = row[j] + min(dp[j], dp[j+1]). Then dp[0] is the answer.

Bottom-up avoids the boundary cases that top-down has (the first and last elements have only one parent), and uses O(n) space where n is the number of rows.

Complexity

Time: O(n²) for n rows. Space: O(n).

Python solution
def minimumTotal(triangle):
    dp = triangle[-1][:]
    for row in reversed(triangle[:-1]):
        for j in range(len(row)):
            dp[j] = row[j] + min(dp[j], dp[j + 1])
    return dp[0]
JavaScript solution
function minimumTotal(triangle) {
  const dp = [...triangle[triangle.length - 1]];
  for (let r = triangle.length - 2; r >= 0; r--)
    for (let j = 0; j <= r; j++) dp[j] = triangle[r][j] + Math.min(dp[j], dp[j + 1]);
  return dp[0];
}