Every DP solution comes down to the same three choices: the state (what one subproblem is, like "the best answer using the first i houses"), the recurrence (how a state is built from smaller ones), and the base cases. Get those right and the code is a few lines, written either top-down with a cache or bottom-up with a table.
When to use it
- The problem asks for a count of ways, a minimum or maximum cost, or whether something is possible.
- A choice at each step (take or skip, which coin, which split) leads to a smaller version of the same problem.
- A plain recursive solution works but times out because it recomputes the same arguments.
- Greedy fails on a small counterexample: the best local choice doesn't lead to the best total.
The template
from functools import cache
def rob(houses): # House Robber
@cache # memoization: each i is solved once
def best(i): # state: best total from house i onwards
if i >= len(houses):
return 0 # base case: no houses left
take = houses[i] + best(i + 2)
skip = best(i + 1)
return max(take, skip) # recurrence: take this house or skip it
return best(0)The variants you will meet
Memoization and tabulation
Top-down memoization adds a cache to the recursive solution; bottom-up tabulation fills a table from the base cases up. Same recurrence, same complexity, and tabulation lets you keep only the last row or two.
1D DP
The state is one index: climbing stairs, house robber, maximum subarray (Kadane's algorithm is a one-variable DP) and longest increasing subsequence.
2D DP
Two indexes, usually a position in each of two strings or a cell in a grid: longest common subsequence, edit distance, unique paths.
Knapsack
Choose items under a capacity. In 0/1 knapsack each item is used once; in unbounded knapsack (coin change) items repeat. Subset sum and partition equal subset sum are knapsack with true/false values.
Intervals, trees, graphs and bitmasks
The state can be a range [i, j] split into two halves, a tree node combining its children, a node in a DAG processed in topological order, or a set of visited items stored as a bitmask.
Time and space complexity
Time is the number of states times the work per state: House Robber has n states with O(1) work, so O(n); edit distance has m·n states, so O(m·n). Space is the number of states you store, often reducible to one or two rows with a rolling array.