Bitmask Dynamic Programming
Bitmask DP is dynamic programming where the state is a subset of a small set, stored as the bits of one integer. It replaces trying every order (n!) with one entry per subset (2ⁿ), which works up to about 20 items.
What Bitmask DP Is
Bitmask DP is dynamic programming whose state is a subset. With n items, bit i of an integer says whether item i is in the subset, so the 2ⁿ subsets are just the integers 0 to 2ⁿ − 1 and can index an array directly.
It fits problems that ask for the best way to use, visit or assign every item of a small set: assign n workers to n jobs, visit every city once, split items into groups. Trying every order costs n!; bitmask dynamic programming keeps one answer per subset instead, which is why it is also called DP over subsets.
The bit operations come from bit manipulation: mask & (1 << i) tests item i, mask | (1 << i) adds it, and popcount(mask) counts how many items are already used.
- One integer = one subset
- Fits n up to about 20
Choosing the State
- Ask what the rest of the problem depends on
- If it is only the set of items used, the state is dp[mask]
- If it also needs the last item, use dp[mask][last]
- Write the move that adds one item, and the starting mask
The key question is whether two partial solutions with the same used set behave the same from here on. In job assignment they do: once jobs 0 and 1 are taken by the first two workers, the remaining choices do not care who took which. So dp[mask] is the cheapest way to give the jobs in mask to the first popcount(mask) workers, and the next worker is popcount(mask).
When the future also depends on where you stopped, add that to the state. A route that has visited the same cities but ends at a different one has different onward costs, so route problems use dp[mask][last]; the travelling salesman problem and Hamiltonian path lessons build that table.
- Same used set, same future → one state
- Add the last item only when it changes the future
Worked Example: Assigning Jobs
Three workers and three jobs, with cost[w][j] = [[9, 2, 7], [6, 4, 3], [5, 8, 1]]. Start with dp[000] = 0. From each mask, worker popcount(mask) tries every job whose bit is still 0: dp[mask | 1 << j] = min(dp[mask | 1 << j], dp[mask] + cost[w][j]).
Mask 011 is reached two ways: worker 0 on job 0 and worker 1 on job 1 (9 + 4 = 13), or the other way round (2 + 6 = 8). The table keeps 8 and forgets 13. That merge is where the saving comes from. The full mask 111 ends at 9: worker 0 takes job 1, worker 1 job 0, worker 2 job 2.
Greedy fails here: worker 0 takes its cheapest job (2), worker 1 its cheapest free job (3), and worker 2 is stuck with 5, for 10. The tracer shows each move.
- Masks only grow, so plain numeric order is a safe loop order
- Store the move that set each value to recover the assignment
Terms, operations, and practical uses
Bits
- MaskAn integer whose bit i is 1 when item i is in the subset. With n items it ranges over 0 to 2ⁿ − 1.
- Full mask(1 << n) − 1, every item used. The answer usually sits at dp[full] or dp[full][last].
- PopcountNumber of set bits. Tells how many items are used, so it can stand in for a worker or position index.
States and moves
- dp[mask]Best value for the used set alone. Enough when the future does not depend on which item came last.
- dp[mask][last]Adds the last item, needed for routes where the next step's cost depends on where you are.
- Adding an itemFrom mask, choose j with bit j clear and move to mask | (1 << j). The new mask is always larger.
Costs
- O(n · 2ⁿ)Time for dp[mask] with n moves per mask. About 21 million steps at n = 20.
- Submask loopsub = (sub − 1) & mask lists every submask; across all masks the total is 3ⁿ.
- SOS DPSum over subsets: aggregates over every submask of every mask in O(n · 2ⁿ).
Code in Python, C++ and Java
cost = [[9, 2, 7], [6, 4, 3], [5, 8, 1]]
n = len(cost)
INF = float("inf")
dp = [INF] * (1 << n)
job = [-1] * (1 << n)
dp[0] = 0
for mask in range(1 << n):
if dp[mask] == INF:
continue
w = bin(mask).count("1")
if w == n:
continue
for j in range(n):
if mask & (1 << j) == 0:
nxt = mask | (1 << j)
if dp[mask] + cost[w][j] < dp[nxt]:
dp[nxt] = dp[mask] + cost[w][j]
job[nxt] = j
full = (1 << n) - 1
print("Minimum cost:", dp[full])
mask, picks = full, []
while mask:
j = job[mask]
mask ^= 1 << j
picks.append(j)
for w, j in enumerate(reversed(picks)):
print(f"worker {w} -> job {j}")#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int>> cost = {{9, 2, 7}, {6, 4, 3}, {5, 8, 1}};
int n = cost.size();
const int INF = 1e9;
vector<int> dp(1 << n, INF), job(1 << n, -1);
dp[0] = 0;
for (int mask = 0; mask < (1 << n); mask++) {
if (dp[mask] == INF) continue;
int w = __builtin_popcount(mask);
if (w == n) continue;
for (int j = 0; j < n; j++) {
if ((mask & (1 << j)) == 0) {
int nxt = mask | (1 << j);
if (dp[mask] + cost[w][j] < dp[nxt]) {
dp[nxt] = dp[mask] + cost[w][j];
job[nxt] = j;
}
}
}
}
int full = (1 << n) - 1;
cout << "Minimum cost: " << dp[full] << '\n';
vector<int> picks;
for (int mask = full; mask; mask ^= 1 << job[mask]) picks.push_back(job[mask]);
for (int w = 0; w < n; w++) cout << "worker " << w << " -> job " << picks[n - 1 - w] << '\n';
}import java.util.*;
class Main {
public static void main(String[] args) {
int[][] cost = {{9, 2, 7}, {6, 4, 3}, {5, 8, 1}};
int n = cost.length;
final int INF = 1_000_000_000;
int[] dp = new int[1 << n], job = new int[1 << n];
Arrays.fill(dp, INF);
dp[0] = 0;
for (int mask = 0; mask < (1 << n); mask++) {
if (dp[mask] == INF) continue;
int w = Integer.bitCount(mask);
if (w == n) continue;
for (int j = 0; j < n; j++) {
if ((mask & (1 << j)) == 0) {
int nxt = mask | (1 << j);
if (dp[mask] + cost[w][j] < dp[nxt]) {
dp[nxt] = dp[mask] + cost[w][j];
job[nxt] = j;
}
}
}
}
int full = (1 << n) - 1;
System.out.println("Minimum cost: " + dp[full]);
List<Integer> picks = new ArrayList<>();
for (int mask = full; mask != 0; mask ^= 1 << job[mask]) picks.add(job[mask]);
for (int w = 0; w < n; w++) System.out.println("worker " + w + " -> job " + picks.get(n - 1 - w));
}
}Step through it
Running on cost = [[9, 2, 7], [6, 4, 3], [5, 8, 1]]
Time and Memory
Masks only gain bits, so every predecessor of a mask is a smaller number and the loop for mask in 0 .. 2ⁿ − 1 visits them first. dp[mask] needs O(2ⁿ) memory and O(n · 2ⁿ) time; dp[mask][last] needs O(n · 2ⁿ) memory and O(n² · 2ⁿ) time.
Memory often runs out before time. dp[mask][last] with n = 20 and 4-byte values is 20 × 2²⁰ × 4 bytes, about 84 MB; n = 25 would need over 3 GB. When the work only depends on popcount, drop the extra dimension.
| n | Orders (n!) | dp[mask] moves (n · 2ⁿ) |
|---|---|---|
| 10 | 3,628,800 | 10,240 |
| 20 | 2.4 × 10¹⁸ | about 21 million |
| 25 | 1.6 × 10²⁵ | about 839 million |
- Numeric order works because adding a bit makes the number bigger
- Size the table before you allocate it
Submask Enumeration
Some problems move from a mask to any part of it, for example splitting items into groups where dp[mask] tries every group sub ⊆ mask. The loop sub = mask; while sub > 0: ...; sub = (sub − 1) & mask visits every non-empty submask of mask in decreasing order and nothing else. Subtracting 1 clears the lowest set bit and sets the bits below it; the & keeps only bits that belong to mask.
Over all masks this costs O(3ⁿ), not 4ⁿ: for each item there are three cases (not in mask, in mask but not in sub, in both). At n = 15 that is about 14 million steps. Handle sub = 0 separately if the recurrence needs it, since the loop stops before it.
When the task is a sum over all submasks of every mask, SOS DP (sum over subsets) does it in O(n · 2ⁿ) by adding one bit dimension at a time.
- (sub − 1) & mask steps to the next smaller submask
- All mask and submask pairs: 3ⁿ
Common Bugs and Edge Cases
Operator precedence. In C and C++, mask & 1 << j == 0 parses as mask & ((1 << j) == 0); Java rejects it outright. Bracket every bit test: (mask & (1 << j)) == 0. Use 1L << j or 1LL << j once n can reach 31.
Worker not tied to the mask. If the code tries every worker from every mask, one worker can take two jobs; in the worked example this reports 8, a cost that no valid assignment has. Take the worker from popcount(mask), or add it to the state.
Complements. ~mask sets every high bit too. Use full ^ mask with full = (1 << n) − 1 to get the unused items.
Test n = 0 and n = 1, an infinity value that does not overflow when a cost is added, and compare with a brute force over all n! orders for n up to 7.
- Bracket every bit test
- Complement with full ^ mask, not ~mask
- Check against brute force for small n