Dynamic Programming21 sections · 916 units
Open in Course

The Bitmask DP Pattern

Dp[mask] indexed by subsets

The core idea: dp[mask]dp[\text{mask}] = answer for the subset represented by mask. Your DP (dynamic programming) table has 2n2^n entries, one per subset. Transitions typically add or remove one element, connecting dp[mask]dp[\text{mask}] to dp[mask with one bit changed]dp[\text{mask with one bit changed}].

You build larger subsets from smaller ones, or vice versa. Time complexity is typically O(n2n)O(n \cdot 2^n) if each state checks nn transitions, or O(n22n)O(n^2 \cdot 2^n) if transitions involve pairs. For n=20n = 20, that's 2020 million or 400400 million operations, both feasible.