Handbooks / Data Structures & Algorithms / Chapter 8
Dynamic Programming and Greedy
7 pages · ~5 min✓ Reviewed
Builds on Intervals and Sweep Line. Next up: Bit Manipulation.
Recursion and the DP Mental Model
1. Recursion
- Recursion = base case + recursive case that shrinks the problem
- Missing or unreachable base case → stack overflow
- Each call gets its own stack frame; depth n costs O(n) space
- Python's default limit is ~1000 frames, then
RecursionError
2. When DP Applies
- Overlapping subproblems: the same state is needed again and again
- Optimal substructure: the best answer is built from best sub-answers
- Both must hold, otherwise DP is the wrong tool
| Naive fib | DP fib | |
|---|---|---|
| Recurrence | fib(n-1) + fib(n-2) | same recurrence |
| Time | O(2^n) | O(n) |
| Why | same subproblems recomputed | each state solved once |
3. The DP Recipe
- Statewhat dp[i] means
- Recurrencefrom smaller states
- Base casessmallest states
- Orderdeps first
- Answerread off dp