Algorithms Playbook
PatternTime O(n · k) · Space O(n)10 min read

Dynamic programming: from recursion to a table

DP is recursion that remembers its answers. How to find the state, write the recurrence, and turn it into a table, with climbing stairs and coin change.

In short

If a recursive solution solves the same subproblem many times, store each answer once. Define dp[i] (what it means), write how it depends on smaller entries, fill it from the base case up. Time = number of states × work per state.

The idea: stop recomputing

Climbing stairs: you can take 1 or 2 steps; how many ways to reach step n? Ways to reach n = ways to reach n−1 + ways to reach n−2. Written as plain recursion that's the Fibonacci tree: ways(30) recomputes ways(2) hundreds of thousands of times.

DP fixes that with one idea: each subproblem is solved once and remembered. Either top-down (recursion + memo dictionary) or bottom-up (a table filled from the smallest case). They compute the same thing.

# top-down: recursion + cache
@cache
def ways(n):
    if n <= 1: return 1
    return ways(n - 1) + ways(n - 2)

# bottom-up: a table
dp = [1, 1]
for i in range(2, n + 1):
    dp.append(dp[i - 1] + dp[i - 2])

The 4-step recipe

  1. State: say in words what dp[i] means (e.g. "fewest coins to make amount i").
  2. Recurrence: how dp[i] comes from smaller states (e.g. min(dp[i - c] + 1) over each coin c).
  3. Base case: the entries you know for sure (dp[0] = 0).
  4. Order and answer: fill from small to large, and say which entry is the answer (dp[amount]).
Coin change: build the table from small amounts up
Speed
001∞2∞3∞4∞5∞6∞coins = {1, 3, 4}
1def coin_change(coins, amount):
2 INF = amount + 1
3 dp = [0] + [INF] * amount
4 for a in range(1, amount + 1):
5 for c in coins:
6 if c <= a:
7 dp[a] = min(dp[a], dp[a - c] + 1)
8 return dp[amount] if dp[amount] < INF else -1
dp[a] = fewest coins to make amount a. dp[0] = 0 (nothing needed); the rest start at ∞ ("not reachable yet").

Variables

amount6
coins1,3,4
Step 1/21· Updates: 0
Try coins 1, 3, 4 with amount 6: greedy (take the biggest coin) picks 4+1+1 = 3 coins, but the table finds 3+3 = 2. That is why this needs DP, not greedy.

When is it DP?

  • You're asked for a count, minimum, maximum or a yes/no ("is it possible?"), not for the list of solutions.
  • Each decision leaves a smaller version of the same problem (optimal substructure).
  • The same subproblems repeat (overlapping subproblems). If they don't, plain divide and conquer is enough.
  • Greedy fails on a small example (coins 1, 3, 4 with amount 6).

Key takeaways

  • 01DP = recursion + remembering answers; each subproblem is solved once.
  • 02Write what dp[i] means before writing any code.
  • 03State, recurrence, base case, order. The cost is states × work per state.
  • 04If dp[i] only needs the last few entries, drop the table and keep variables.

Check your understanding

1 of 3

What makes a problem a good fit for DP?

Related topics