Dynamic programming · 4 / 15 Theory

DP on grids and triangles

When the problem lives on a grid or a triangle, the state is the coordinates (i, j). If you can only move right and down, each square depends on the one above and the one to the left.

def min_cost(m):
    f, c = len(m), len(m[0])
    dp = [[0] * c for _ in range(f)]
    for i in range(f):
        for j in range(c):
            if i == 0 and j == 0:
                dp[i][j] = m[0][0]
            else:
                up = dp[i - 1][j] if i > 0 else float("inf")
                left = dp[i][j - 1] if j > 0 else float("inf")
                dp[i][j] = m[i][j] + min(up, left)
    return dp[-1][-1]

print(min_cost([[1, 3, 1], [1, 5, 1], [4, 2, 1]]))   # 7

def triangle_sum(triangle):
    dp = triangle[-1][:]                     # bottom row
    for row in range(len(triangle) - 2, -1, -1):
        dp = [triangle[row][j] + max(dp[j], dp[j + 1]) for j in range(row + 1)]
    return dp[0]

print(triangle_sum([[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]))   # 23
  • For the edges use float("inf") as “you cannot come from there” when minimizing (or 0/-inf when maximizing).
  • In the triangle it is best to compute from the bottom up: that way the top ends up with the answer and there are no special cases.
  • Counting paths (as in Backtracking) and optimizing them use the same table; the operation changes: adding versus min/max.

You practice it in Minimum cost path and Number triangle.