Dynamic Programming
Tactic
Dynamic programming defines a state, a recurrence, base cases, and an evaluation order. Each state answers one reusable subproblem.
The invariant is that every state is solved from smaller or already known states. In top-down form, the call stack discovers states and a cache remembers them. In bottom-up form, the table order guarantees dependencies are ready.
The main skill is state design. A state should include exactly the information needed to make the remaining decision independent of the earlier path. Too little state gives wrong reuse. Too much state explodes time and space.
Value
The value is controlled reuse. DP turns repeated search into a table of unique questions, which is why it often converts exponential recursion into polynomial time.
Direct complexity example
- Brute force: Explore all decision paths in a recursion tree: often or worse, with repeated subproblems.
- With this tactic: Cache each unique state once: time.
- Space: Space is for the cache or table, sometimes reducible with state compression.
Challenges this solves
- counting ways
- minimum cost
- maximum score
- sequence alignment
- choice with constraints
- grid paths
When to use it
Use this tactic when these conditions are true:
- the brute force asks the same suffix or subproblem many times
- the answer for a larger problem can be built from smaller answers
- the prompt asks for min, max, count, or feasibility
- a greedy rule is tempting but not provable
When not to use it
Reach for a different tactic when these warning signs appear:
- there is no overlapping subproblem structure
- a simple scan or greedy invariant keeps all needed information
- the state space is too large and needs a different model
- the recurrence depends on future choices in a cyclic way
Terminology clues
These prompt words often point toward this concept:
- number of ways
- min cost
- max profit
- can form
- choose or skip
- optimal substructure
- overlapping subproblems
- recurrence
Problems that use it
- 70. Climbing Stairs
- 72. Edit Distance
- 91. Decode Ways
- 97. Interleaving String
- 115. Distinct Subsequences
- 152. Maximum Product Subarray
- 198. House Robber
- 213. House Robber II
- 300. Longest Increasing Subsequence
- 309. Best Time to Buy and Sell Stock with Cooldown
- 312. Burst Balloons
- 322. Coin Change
- 329. Longest Increasing Path in a Matrix
- 337. House Robber III
- 338. Counting Bits
- 416. Partition Equal Subset Sum
- 518. Coin Change II
- 714. Best Time to Buy and Sell Stock with Transaction Fee
- 746. Min Cost Climbing Stairs
- 907. Sum of Subarray Minimums
- 968. Binary Tree Cameras
- 1143. Longest Common Subsequence