β When to think DP?
- Count total ways
- Find minimum
- Find maximum
- βTry all possible choicesβ
Try all possible choices β Recursion β DP
- We use it when greedy fails
π 3-Step Trick
1. Define the State
Represent the problem using an index/state.
f(i) = Answer for state i2. Find All Choices
List every possible move from that state.
Choice 1
Choice 2
...3. Combine Results
- Count ways β
+ - Minimum β
min() - Maximum β
max() - Possible? β
||return trueorreturn false
π Climbing Stairs
State
f(i) = Ways to reach stair iChoices
i-1
i-2Combine
f(i) = f(i-1) + f(i-2)Base Cases
f(0) = 1
f(i < 0) = 0