Dynamic Programming
Solve each subproblem once and reuse the answer: memoization, tables, knapsack, string DP and more.
- Overlapping subproblems and memoization Memoization stores each subproblem’s answer the first time it is computed. Repeated subtrees of the recursion tree collapse into cache hits.
- Tabulation: filling the table bottom-up Tabulation fills a table from the smallest subproblems up, so every value it needs is already there. Watch the table fill left to right.
- The DP recipe: state, transition, base cases, order, answer Every DP answers five questions: the state, the transition, the base cases, the fill order and where the answer lives.
- 1-D DP: house robber, decode ways, jump game II One-dimensional DP keeps one value per position, built from the previous one or two, as in house robber and decode ways.
- Kadane's algorithm and maximum subarray Kadane’s algorithm finds the maximum subarray in one pass by tracking the best sum ending here and the best seen so far.
- 0/1 and unbounded knapsack Knapsack picks items to maximise value within a weight limit. A table row per item records whether taking or skipping each item is better.
- Coin change: minimum coins and number of ways Coin change finds the fewest coins for an amount, or the number of ways to make it. Each coin sweeps across the amounts table.
- Longest increasing subsequence; the n log n version The longest increasing subsequence has an O(n²) table solution and an O(n log n) version that keeps a tails array and binary searches it.
- Grid DP: paths, minimum path sum, obstacles Grid DP computes each cell from the cells above and to the left, counting paths or finding the cheapest path around obstacles.
- String DP: LCS, edit distance, palindromic subsequence Two-string DP puts one string on each axis of a table. Longest common subsequence and edit distance fill it cell by cell, moving…
- Space optimization: rolling rows and variables Most DP tables only need the last row or two. Rolling arrays shrink a grid to two rows, then to one, without changing the answer.
- Interval DP: matrix chain, burst balloons, palindrome partitioning Interval DP solves every subrange, shortest first, combining smaller ranges, as in matrix chain order and burst balloons.
- State machine DP: stock problems State machine DP tracks which state you are in on each day, such as holding, sold or cooling down, to solve stock trading problems.
- Bitmask DP: TSP and assignments Bitmask DP uses the bits of an integer to record which items are used, solving the travelling salesperson and assignment problems for…
- Tree DP Tree DP computes answers for each subtree from its children’s answers, as in house robber on a tree and placing cameras.
- Recognizing DP and choosing the state Spot when a problem needs DP: optimal or counting answers built from overlapping choices. Then pick a state that captures what matters.