CodingNodes / 2-D Dynamic Programming / Triangle System design Space play · ←→ step · R restart

Problem

A triangle of numbers has r + 1 numbers in row r (row 0 has one number). You start at the top and walk down to the last row. From the number at position c in a row you may step to the number at position c or c + 1 in the row below.

Return the smallest possible sum of the numbers you visit on the way down.

Constraints

  • 1 ≤ triangle.length ≤ 200
  • triangle[r].length = r + 1
  • −10⁴ ≤ triangle[r][c] ≤ 10⁴

Examples: pick one to animate

Solutions

TimeO(n²) SpaceO(n²)

Time: The triangle has about n²/2 numbers, and each is handled once with one comparison.

Space: The dp table is a full copy of the triangle, about n²/2 numbers.

dp[r][c] is the cheapest total from cell (r, c) down to the last row. Start with the bottom row as is, then go up: dp[r][c] = triangle[r][c] + min(dp[r+1][c], dp[r+1][c+1]). The top cell is the answer.