2D DP: Grids and Knapsack
Extend DP to two dimensions for grid paths and to the knapsack family of choose-or-skip problems with capacity constraints.
Intermediate · about 8 hours · difficulty 4/5
Learn first: Dynamic Programming Foundations (1D)
Many DP problems need two indices in the state. Two families cover most of them: grid DP and knapsack.
Grid DP
State dp[i][j] is the answer for reaching (or starting from) cell (i, j). Transitions come from neighbours such as up and left.
- Unique Paths, Unique Paths with obstacles, Minimum Path Sum, Triangle, Dungeon Game (fill from the bottom-right), and Cherry Pickup (advanced, two walkers).
- Space can usually be reduced to one row.
0/1 knapsack
Each item is taken at most once. State dp[i][w] = best value using the first i items with capacity w. Transition: skip item i, or take it if it fits: max(dp[i-1][w], dp[i-1][w - wt] + val). With a 1D array, iterate w downwards so each item is used once.
Knapsack in disguise is extremely common:
- Subset sum / Partition Equal Subset Sum (boolean knapsack).
- Target Sum (count subsets with a given difference).
- Last Stone Weight II.
Unbounded knapsack
Items can be reused: iterate w upwards in the 1D version. Coin Change II (count combinations) and Rod Cutting are the classics. Loop order matters: items outer, amount inner counts combinations; amount outer counts permutations.
Good enough to move on: you can explain why the direction of the inner loop decides between 0/1 and unbounded knapsack.
Key concepts
- Grid path DP
- Row-based space optimisation
- 0/1 knapsack
- Subset sum and partition
- Unbounded knapsack
- Combinations vs permutations loop order
- Multi-walker grid DP: Cherry Pickup
Mini project
Solve 9 problems: Unique Paths II, Minimum Path Sum, Triangle, Partition Equal Subset Sum, Target Sum, Coin Change II, Last Stone Weight II, Ones and Zeroes, and CSES Book Shop.
Check yourself
In the 1D-array version of 0/1 knapsack, what goes wrong if you iterate capacity from small to large?
Free resources
- Knapsack problem (cp-algorithms)
- CSES Problem Set (Dynamic Programming) (CSES)
- NeetCode Roadmap (2-D DP) (NeetCode)