Dynamic Programming
Dynamic programming (DP) solves a big problem by solving smaller overlapping problems once and storing their answers. Two styles: top-down (recursion + memo) and bottom-up (fill a table).
Dynamic programming is for problems where the same smaller questions come up again and again. By saving each answer the first time, you avoid repeating work - often turning exponential time into linear. The hard part is defining the right smaller question; practice makes this much easier.
Climbing stairs
You can climb 1 or 2 steps at a time. How many ways to reach step n? Ways(n) = Ways(n-1) + Ways(n-2).
Example
Coin change: fewest coins
Example
0/1 knapsack: best value within a budget
Example
Longest common subsequence
Example
To spot DP: the question asks for a count, a minimum or a maximum, and choices at each step lead to smaller versions of the same question. Write the recurrence first, then code it.
Key points
- Define what dp[x] means in words.
- Build it from smaller answers (memoization or a table).
- Classic problems: Fibonacci, coin change, knapsack, LCS.
📝 Test yourself
1. What makes a problem a good fit for DP?
2. In 0/1 knapsack, why loop the budget backwards?
3. Fill in the decorator that adds memoisation:
@functools.
def ways(n): ...
