DSA Master › Topic 14
Dynamic Programming
DP is recursion plus caching. Start with the brute-force recursion, memoize it, then turn it into a bottom-up table if you need to. For every problem, answer four questions: what the state is, what the transition is, what the base cases are, and what order to fill the table in. Aim to recognise these, not to memorise solutions.
Concepts
- 1D DP
- 2D / Grid DP
- Knapsack DP
- Subsequence DP
- String DP
- State-machine DP
- Interval DP
How to recognise it
- The problem asks for the number of ways, a min/max cost, or whether something is possible.
- The choices at each step overlap. The same subproblem comes up again and again.
- Two strings or sequences are compared (LCS, edit distance), which usually means a 2D table.
Common pitfalls
- In 0/1 knapsack with a 1D array, loop capacity backwards. Coin Change II, which allows unlimited use, loops forwards.
- Write the recursion and memoize it before you jump to a table.
Problems
- Climbing Stairs (Easy)
- Min Cost Climbing Stairs (Easy)
- House Robber (Medium)
- House Robber II (Medium)
- Coin Change (Medium)
- Coin Change II (Medium)
- Maximum Subarray (Medium)
- Longest Increasing Subsequence (Medium)
- Longest Common Subsequence (Medium)
- Edit Distance (Medium)
- Word Break (Medium)
- Partition Equal Subset Sum (Medium)
- Target Sum (Medium)
- Unique Paths (Medium)
- Unique Paths II (Medium)
- Minimum Path Sum (Medium)
- Best Time to Buy and Sell Stock (Easy)
- Best Time to Buy and Sell Stock with Cooldown (Medium)
- Burst Balloons (Hard)
- Regular Expression Matching (Hard)