Learn the pattern · ~15 min
Bitmask DP
also called subset DP, TSP DP, Held-Karp, broken profile, DP on Broken Profile
When n is tiny (about 20 or less) and the future depends only on which items are used (and maybe the last one), store the used set as the bits of an integer and DP over the 2ⁿ sets instead of the n! orders.
Reach for it when you read
- +n ≤ about 20 and every item is used exactly once: visit every city, give every worker one job.
- +Split up to about 16 items into groups or buckets with equal sums.
- +The brute force tries all n! orders, but the future only cares which items are left (and maybe the last one).
- +A two-player game that takes numbers from a small shared pool.
- +Narrow grid rows (width ≤ about 10) where one row's pattern limits the next.
Not this one when
- ×n in the thousands: 2ⁿ is out of reach. Look for sorting, greedy or a DP on counts.
- ×Items may be used any number of times and order doesn't matter: knapsack.
- ×You must list every subset itself: backtracking, there are no shared states to reuse.
Learn Bitmask DP
First, what is a bitmask?
A bitmask stores a set of small numbers as the bits of one integer. Bit i is 1 when item i is in the set. Read the bits from the right: bit 0 is the last digit.
So with four cities, 0101 means cities 0 and 2 are in, and 1 and 3 are out. As a plain number that's 5. Every set of 4 cities is one number from 0 (0000, nobody) to 15 (1111, everybody).
Bitmask DP uses that number as a table index: one answer per set. For n up to about 20, the 2ⁿ sets are few enough.
Building a set, bit by bit
Start empty and add cities one at a time:
| step | what happens | mask | number |
|---|---|---|---|
| start | no city yet | 0000 | 0 |
| add city 0 | turn on bit 0 | 0001 | 1 |
| add city 2 | turn on bit 2 | 0101 | 5 |
| is city 1 in? | look at bit 1: it's 0 | 0101 | 5 |
| add city 1 | turn on bit 1 | 0111 | 7 |
| how many? | count the 1 bits | 0111 | 3 cities |
Adding a city only turns a bit on, so the number only grows. That will matter for the loop order.
The code for it
int mask = 0; // 0000: empty
mask |= 1 << 0; // add city 0 → 0001
mask |= 1 << 2; // add city 2 → 0101
int in1 = mask >> 1 & 1; // is city 1 in? → 0
mask |= 1 << 1; // add city 1 → 0111
int cnt = __builtin_popcount(mask); // how many → 3You don't need to memorise this. It's the table above: 1 << i is a number with only bit i on, | turns it on, and >> i & 1 reads it.
Why not a vector<bool>? Because a mask is a number: it indexes an array directly, dp[mask], and copying it costs nothing.
Fine, but how does this help us?
Here's a classic problem: the travelling salesman. Start at city 0, visit every city exactly once, come back to 0, and make the trip as short as possible:
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| 0 | 0 | 2 | 9 | 3 |
| 1 | 2 | 0 | 4 | 7 |
| 2 | 9 | 4 | 0 | 5 |
| 3 | 3 | 7 | 5 | 0 |
With four cities there are only six orders after city 0, so try them all:
tour legs total
0 1 2 3 0 2 + 4 + 5 + 3 14
0 1 3 2 0 2 + 7 + 5 + 9 23
0 2 1 3 0 9 + 4 + 7 + 3 23
0 2 3 1 0 9 + 5 + 7 + 2 23
0 3 1 2 0 3 + 7 + 4 + 9 23
0 3 2 1 0 3 + 5 + 4 + 2 14The answer is 14: 0 → 1 → 2 → 3 → 0, or the same loop backwards.
The brute force
The choices: which unvisited city comes next. The recursion carries the cities visited so far (a mask) and where you stand, and returns the cheapest way to finish.
int go(int mask, int last) { // cheapest way to finish from here
if (mask == full) return d[last][0]; // everyone visited: go home
int best = INF;
for (int nxt = 0; nxt < n; nxt++)
if ((mask >> nxt & 1) == 0) // not visited yet
best = min(best, d[last][nxt] + go(mask | 1 << nxt, nxt));
return best;
}
// answer: go(1, 0), only city 0 visitedDraw a corner of the calls, from city 0 (mask 0001):
- go(0001, at 0)
- to 1 → go(0011, at 1)
- to 2 → go(0111, at 2) → to 3 → go(1111, at 3) = go home: 3
- to 3 → go(1011, at 3) → to 2 → go(1111, at 2) …
- to 2 → go(0101, at 2)
- to 1 → go(0111, at 1) → to 3 → go(1111, at 3)← again
- to 3 → …
That's 16 calls for 4 cities, but it's every order: for 16 cities about 3.6 × 10¹² calls, more than the 15! ≈ 1.3 × 10¹² orders. Already 13 cities take 7 s. Time limit exceeded.
The one thought: the order is forgotten
Point at the two go(1111, at 3) calls. One walked 0 → 1 → 2 → 3, spending 11. The other walked 0 → 2 → 1 → 3, spending 20.
What's left for each? The same: every city is done, they stand at 3, and the only move is home, cost 3. The future doesn't care about the order. It only needs which cities are done and where you are. So the 20 can never beat the 11.
That's one question per (set, city): 2ⁿ · n of them. For n = 16, about a million, instead of 10¹² orders.
Memoise it
int goMemo(int mask, int last) { // memo starts as all -1
if (mask == full) return d[last][0];
if (memo[mask][last] != -1) return memo[mask][last]; // asked before
int best = INF;
for (int nxt = 0; nxt < n; nxt++)
if ((mask >> nxt & 1) == 0)
best = min(best, d[last][nxt] + goMemo(mask | 1 << nxt, nxt));
return memo[mask][last] = best;
}The bottom-up table
Flip the question: dp[mask][last] = the cheapest walk from 0 that has visited exactly mask and ends at last. A move only turns a bit on, so the new mask is always bigger. Loop masks upwards and every state is final before you extend it.
vector<vector<int>> dp(1 << n, vector<int>(n, INF));
dp[1][0] = 0; // only city 0 visited, standing at 0
for (int mask = 1; mask < (1 << n); mask++) // a move only makes the mask bigger
for (int last = 0; last < n; last++) {
if (dp[mask][last] == INF) continue; // can't be here
for (int nxt = 0; nxt < n; nxt++) {
if (mask >> nxt & 1) continue; // already visited
int nm = mask | 1 << nxt;
dp[nm][nxt] = min(dp[nm][nxt], dp[mask][last] + d[last][nxt]);
}
}
int best = INF;
for (int last = 1; last < n; last++) best = min(best, dp[full][last] + d[last][0]);Dry run
Same distances. Each row is a set (bit 0, city 0, is always on); a blank cell means "can't end there".
| mask | at 1 | at 2 | at 3 | what happens |
|---|---|---|---|---|
| 0011 | 2 | 0 → 1 | ||
| 0101 | 9 | 0 → 2 | ||
| 1001 | 3 | 0 → 3 | ||
| 0111 | 13 | 6 | at 2: 2 + 4 from 1; at 1: 9 + 4 from 2 | |
| 1011 | 10 | 9 | at 3: 2 + 7; at 1: 3 + 7 | |
| 1101 | 8 | 14 | at 2: 3 + 5; at 3: 9 + 5 | |
| 1111 | 12 | 14 | 11 | at 3: min(13 + 7, 6 + 5) = 11 |
Home from 1111: 12 + 2, 14 + 9, 11 + 3. The best is 14, the same answer as the brute force.
Why it's O(2ⁿ · n²)
Count the states, not the loops: 2ⁿ masks times n last cities, and each state tries n next cities. So O(2ⁿ · n²) time: for n = 16, about 1.7 × 10⁷ steps. The table is O(2ⁿ · n) space.
From n! orders down to 2ⁿ · n², by forgetting the order and keeping only the set.
Pair two lists? The count is the position
Minimum XOR Sum of Two Arrays: match each x[i] with a different y[j]. Fill x in order, so the next x to match is popcount(mask), and no last is needed:
int i = __builtin_popcount(mask); // how many x's are matched already
dp[mask | 1 << j] = min(dp[mask | 1 << j], dp[mask] + (x[i] ^ y[j]));For x = [2, 5, 1], y = [4, 1, 7]: 6 (2 with 7, 5 with 4, 1 with 1).
Remember this
- n ≤ about 20 and each item is used or assigned once → a mask.
- State = the set, plus what the future needs (often the last item).
- Check memory: n = 20 gives 2²⁰ · 20 ≈ 2 × 10⁷ ints, about 84 MB.
- Trap:
mask & 1 << k == 0parses asmask & ((1 << k) == 0). Bracket it:(mask >> k & 1) == 0. - Whenever n is tiny and the brute force tries every order, ask "does the future need the order, or only the set?" If only the set, it's this.
Practise it on Can I Win (a game over a set), then Partition to K Equal Sum Subsets, Minimum XOR Sum of Two Arrays (no last item), Shortest Path Visiting All Nodes (revisits allowed: BFS over states) and Find the Shortest Superstring (rebuild the answer).
Watch it work, line by line
Travelling Salesman (shortest tour), d = [[0,10,15,20],[10,0,35,25],[15,35,0,30],[20,25,30,0]] → 80 (0 → 1 → 3 → 2 → 0). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Is n tiny (about 20 or less), and does what's left depend only on which items I've already used (and maybe the last one), not on the order I used them in?
Reach for it when
- +n <= 20 (sometimes 15-16 with extra factor)
- +visit/assign/order a small set
- +Hamiltonian path / TSP
- +2n * n2 <= ~1e8-4e8
It fails when
- ×n > ~25, 2ⁿ blows upuse Meet in the middle, or greedy
- ×Items are interchangeable, so counts sufficeuse Knapsack-style DP over counts
Looks like it, isn't (and the other way round)
- Partition to K Equal Sum Subsets looks like 0/1 Knapsack, needs this pattern
k buckets cannot be tracked by a single capacity; use bitmask DP or pruned backtracking.
- Parallel Courses II looks like Topological Sort, needs this pattern
Greedy picking of available courses per semester is wrong; n <= 15 invites DP over taken masks.
- Minimum XOR Sum of Two Arrays looks like Greedy, needs this pattern
Assignment with n <= 14. Greedy pairing fails. dp[mask] over the matched elements of nums2 (Hungarian / min-cost-flow also works).
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1What does
dp[mask][last]mean in TSP?RevealThe shortest path from the start that visits exactly the places in mask and ends at last.
2Why is looping masks from 0 upward a valid order?Reveal
Adding an item sets a bit, which always makes a bigger number, so every state is final before anything is built from it.
3Roughly how big can n be for
dp[mask][last]?RevealAbout 20. The work is 2ⁿ · n² ≈ 4.2 × 10⁸ at n = 20 with an 80 MB
inttable; at n = 22 it's 2.0 × 10⁹ steps and 352 MB, past most limits.4How do you test bit i, add item i, and remove item i?Reveal
Test:
(mask >> i) & 1. Add:mask | (1 << i). Remove:mask & ~(1 << i). Parenthesise:==binds tighter than&.
Practice ladder
- 1Can I Wingame over a setMedium
- 2Partition to K Equal Sum Subsetsfill bucketsMedium
- 3Elevator Ridesfill bucketsMedium
- 4Hamiltonian Flightscount pathsHard
- 5Minimum XOR Sum of Two ArraysassignmentHard
- 6Shortest Path Visiting All NodesrevisitsHard
- 7Parallel Courses IIgroups per stepHard
- 8Find the Shortest Superstringrebuild the answerHard
Finished Bitmask DP? Mark it done and Lessgo moves you to the next step.