Dynamic programming
Dynamic programming (DP) solves a problem by combining answers to overlapping subproblems, storing each subproblem's result once. Memoised recursion and bottom-up tables are the two usual forms.
Detailed Explanation
Naive recursion recomputes the same subproblem. Fibonacci without storage is exponential because fib(n-2) is computed from both fib(n) and fib(n-1). DP is the decision to store fib(k) the first time you know it.
The recipe is: name the state, write the recurrence, choose a base case, then either memoize the recursive function or fill an array in an order that respects dependencies. State is the tuple of parameters that identify a subproblem: (index, remaining_capacity) for a knapsack, (i, j) for a pair of prefixes in edit distance.
Top-down DP is a recursive function plus functools.cache or a dict. It only computes states you need. Bottom-up DP allocates a table and loops. It has no recursion-limit issue and is often easier to reason about for time complexity: states times work per state.
You must prove overlapping subproblems and optimal substructure. If subproblems do not overlap, you have divide-and-conquer, not DP. If a local optimum does not extend, you may want greed or search.
Space can often shrink. A recurrence that only needs the previous row uses two rows, or one. Fibonacci needs two scalars. Do not keep an n×n table when the next value only depends on a neighbour.
In Python, cache on a function with mutable arguments will not hash. Use tuples. Integer states as list indices are faster than a dict of tuples when the ranges are dense and known.
Code Examples
from functools import cache
@cache
def fib(n: int) -> int:
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(10)) # 55def knapsack(values: list[int], weights: list[int], cap: int) -> int:
n = len(values)
dp = [0] * (cap + 1)
for i in range(n):
w, v = weights[i], values[i]
for c in range(cap, w - 1, -1): # backward so each item is used once
dp[c] = max(dp[c], dp[c - w] + v)
return dp[cap]
print(knapsack([6, 10, 12], [1, 2, 3], 5)) # 22Common Gotchas
Forgetting the base case
memoisation caches a crash, or recursion never ends.
Forward update on a 0-1 knapsack row
you reuse the same item. Iterate capacity downward.
`@cache` on unbounded input grows without bound
use `@lru_cache(maxsize=...)` or a table you control.
Time is `|states| × work`
if you cannot count the states, you cannot claim the complexity.