DP on Grids & Advanced Patterns
The Mental Model
Advanced DP builds on fundamentals with more complex state representations. Grid DP adds spatial dimensions, interval DP considers ranges, and bitmask DP encodes subset information. The core principle remains: define state, find transitions, handle base cases.Pattern Recognition Signals:
- Grid traversal with optimization → Grid DP
- “Merge” or “split” segments → Interval DP
- Small n (≤ 20) with subset selection → Bitmask DP
- “Partition into groups” → Bitmask DP
Pattern 1: Grid DP
State: dp[i][j] = answer for cell (i, j)Unique Paths
Problem: Count paths from top-left to bottom-right, moving only right or down.Minimum Path Sum
Problem: Find minimum sum path from top-left to bottom-right.Grid with Obstacles
Pattern 2: Interval DP
State: dp[i][j] = answer for the interval [i, j] Key Insight: Solve for small intervals first, then larger ones. Often involves choosing a split point k. The Template:Matrix Chain Multiplication
Problem: Minimize cost to multiply chain of matrices. Why order matters: Multiplying matrices A(10×30), B(30×5), C(5×60):- (AB)C: 10×30×5 + 10×5×60 = 1500 + 3000 = 4500 operations
- A(BC): 30×5×60 + 10×30×60 = 9000 + 18000 = 27000 operations
Palindrome Partitioning
Problem: Minimum cuts to partition string into palindromes.Burst Balloons
Problem: Burst balloons to maximize coins. Bursting balloon i gives nums[left] * nums[i] * nums[right] coins. Key Insight: Think backwards—which balloon do we burst last in a range?Pattern 3: Bitmask DP
State: dp[mask] where mask is a binary representation of a subset. When to Use: n ≤ 20 (since 2^20 ≈ 10^6)Traveling Salesman Problem (TSP)
Problem: Visit all cities exactly once and return to start with minimum cost.Counting Subsets
Problem: Partition n elements into groups, each group following rules.Bitmask Tricks
Pattern 4: DP with Optimization
Prefix Sum Optimization
When transition involves sum over range, precompute prefix sums.Monotonic Queue Optimization
When dp[i] = min/max(dp[j] + cost(j, i)) for j in sliding window.Common Mistakes
Practice Problems
Grid DP (1300-1500)
Interval DP (1500-1700)
Bitmask DP (1600-1900)
Key Takeaways
Grid = 2D State
dp[i][j] represents answer at position (i, j).
Interval = Small to Large
Solve small intervals first, combine for larger.
Bitmask = Subset
When n ≤ 20, encode subset selection in bits.
Think Backwards
Sometimes easier to think “what happens last?”
Next Up
Chapter 13: Graph Fundamentals
Enter the world of graphs—the most versatile data structure in competitive programming.