Dynamic Programming (1-D)
Signal: "number of ways", "minimum/maximum cost", "is it possible", over choices that build on smaller versions of the same problem, where brute-force recursion recomputes the same subproblems again and again.
Core idea: DP = recursion + memory. Two conditions make it work:
- Optimal substructure: the answer for
iis built from answers to smaller subproblems. - Overlapping subproblems: the same subproblems recur, so computing each once turns exponential time into polynomial time.
The 4-step recipe
- State: what does
dp[i]mean? (Write it in one sentence. This is the hard part.) - Recurrence: how does
dp[i]depend on smaller states? - Base cases.
- Order & answer: fill in an order where dependencies are ready; say which cell is the answer. Then optimize space if only the last few states are needed.
python
# Top-down (memoized recursion): often easiest to write first
from functools import cache
@cache
def f(i):
if i <= 1: return base(i)
return combine(f(i - 1), f(i - 2))
# Bottom-up (tabulation): no recursion limit, easy to space-optimize
dp = [0] * (n + 1)
dp[0], dp[1] = ...
for i in range(2, n + 1):
dp[i] = combine(dp[i - 1], dp[i - 2])| Family | State | Examples |
|---|---|---|
| Linear "steps" | dp[i] = answer for the first i items | Climbing Stairs, House Robber, Decode Ways |
| Unbounded knapsack | dp[amount] | Coin Change, Coin Change II |
| 0/1 knapsack | dp[capacity], iterate capacity backwards | Partition Equal Subset Sum |
| Subsequence | dp[i] = best ending at i | Longest Increasing Subsequence |
| String segmentation | dp[i] = can prefix of length i be split | Word Break |