Bitmask DP & the Held–Karp Algorithm
DP over subsets in O(2ⁿ n²), and broken-profile DP.
Brute force over the tours of 20 cities checks of them. In 1962 Bellman, and independently Held and Karp, noticed that the rest of an optimal tour needs to know only which cities have been visited and where the salesman stands: states. More than sixty years later, no algorithm for the general traveling salesman problem is known to beat by an exponential factor.
What you’ll learn
- State and prove the Held–Karp recurrence, count its entries, , and its time, , and reconstruct an optimal tour.
- Count Hamiltonian cycles in time and polynomial space by inclusion–exclusion, and describe what is known below .
- Compute sums over subsets in with the zeta transform instead of , and state the subset convolution.
- Count tilings with broken-profile DP in , and connect it to transfer matrices and Kasteleyn's formula.
Held–Karp, precisely
Optimal substructure. In a shortest such path to with , let be the city before . The part before is a path from 0 through exactly ending at ; if a shorter one existed, splicing it in would shorten the whole path (cut and paste). Conversely, every and every such path extends by the edge . Hence the minimum over .
Entries. Each of the cities lies in subsets of :
Sums compared. The entry compares candidates, and summing over the sizes of gives per city ; closing the tour adds more:
Reconstruction. Store the minimizing with each entry, or recompute it, and walk back from the best final : more time. Masks in increasing integer order list every set after its subsets, so a single loop over masks is a valid order.
How many table entries does Held–Karp fill for cities?
Show the answer
11264
, against tours for brute force. Each extra city roughly doubles the table, while brute force multiplies its work by .
Below 2ⁿ, and in polynomial space
Held–Karp's weakness is memory: for the table has entries. For the decision version, "is there a Hamiltonian cycle?", counting is the way out. Let be the number of closed walks of length from vertex 0 that use only the vertices of : easy to count by a DP over the walk's length, in polynomial time and space. A closed walk of length from 0 that visits all vertices visits each exactly once: it is a Hamiltonian cycle with a starting point and a direction. Inclusion–exclusion removes the walks that miss a vertex (Kohn, Gottlieb & Kohn, 1977; Karp, 1982; Bax, 1993):
That is polynomial-time counts: time and polynomial space.
A closed walk of length from vertex 0 misses exactly the vertices of a non-empty set . How much does it contribute in total to the inclusion–exclusion sum?
Show the answer
C.
It is counted in exactly for the sets , with sign , and for non-empty . Only walks that miss nothing, the Hamiltonian cycles, survive, each counted once (for ).
Beating . For undirected graphs, Björklund (FOCS 2010; SIAM J. Comput. 2014) decides Hamiltonicity in randomized time by summing determinants over a field of characteristic two, and in on bipartite graphs. For the traveling salesman with weights, Nederlof (STOC 2020) solved bipartite instances in randomized time, assuming matrix multiplication takes essentially quadratic time. For general weighted TSP nothing of the form is known; a 2024 preprint by Stoian removes only a subexponential factor, reaching through fast products.
Sums over subsets
Many bitmask DPs need, for every set , an aggregate over all of its subsets: , the zeta transform of , known in contests as sum over subsets (SOS DP). Enumerating the submasks of every mask costs steps. Adding one bit at a time costs .
Process the bits one at a time. Invariant: after bits have been processed, sums over the subsets that agree with on the bits :
Processing bit : if contains bit , its subsets may now also lack bit , and those are exactly the subsets counted by :
After all bits, , at one pass over the masks per bit. Subtracting instead of adding undoes the passes, which is Möbius inversion, :
def subset_sums(g, n):
"""f[S] = sum of g[T] over all subsets T of S, for every S: O(2^n * n) instead of 3^n."""
f = list(g)
for i in range(n): # let subsets differ from S in bit i too
for S in range(1 << n):
if S >> i & 1:
f[S] += f[S ^ (1 << i)] # add the subsets that lack bit i
return fChecked against direct summation over all submasks for . With max in place of + it computes the best value over all subsets; with the test reversed (if not S >> i & 1: f[S] += f[S | 1 << i]) it sums over supersets.
The harder sibling is subset convolution, , which splits into two disjoint parts; done directly it costs again. Björklund, Husfeldt, Kaski and Koivisto (STOC 2007) computed it with ring operations by ranking the zeta transform by set size, so that disjointness becomes a condition on sizes. It speeds up DPs that build a set out of disjoint groups, such as counting set partitions, and the Steiner tree DP with bounded integer weights. For submask enumeration in code, see Subsets as Bitmasks.
Broken profiles: DP over a moving frontier
How many ways are there to tile an board with dominoes? Fill the cells in row-major order. When the scan reaches a cell, everything before it is covered, and the rest of the board needs to know only which of the next cells are already covered by dominoes sticking out of the filled part: a mask of bits, the profile. It is "broken" because it runs along a staircase, partly in the current row and partly in the next. This is profile DP.
def domino_tilings(n, m):
"""Tilings of an n x m board by 1 x 2 dominoes, cell by cell in row-major order. O(n m 2^m)."""
ways = {0: 1} # profile bit k set: the cell k places ahead is already covered
for cell in range(n * m):
i, j = divmod(cell, m)
nxt = {}
for prof, cnt in ways.items():
if prof & 1: # covered from earlier: move on
options = [prof >> 1]
else:
options = []
if i + 1 < n: # vertical: also covers the cell below
options.append((prof | 1 << m) >> 1)
if j + 1 < m and not prof & 2: # horizontal: also covers the next cell
options.append((prof | 2) >> 1)
for key in options:
nxt[key] = nxt.get(key, 0) + cnt
ways = nxt
return ways.get(0, 0)
print(domino_tilings(8, 8)) # 12988816At most profiles per cell and at most two transitions each: time, with the shorter side. On the board at most 70 profiles are reachable at any one time.
Think first How many domino tilings does a board have?
- The leftmost column is covered either by one vertical domino, leaving a board, or by two horizontal ones, leaving . So with and : the Fibonacci numbers . The profile DP returns 89 too.
Transfer matrices. Processed a whole row at a time, the same DP is a matrix whose entry counts the ways to fill one row when profile comes in and profile goes out, and the number of tilings is . For a fixed width and a huge length , fast matrix powering computes it with arithmetic operations (see Linear Recurrences & Matrix Powers). Statistical physicists call this the transfer-matrix method.
Key takeaways
- Held–Karp: , with entries, time and space; integer order of masks is a topological order.
- Inclusion–exclusion over closed walks counts Hamiltonian cycles in time and polynomial space; Björklund's beats for undirected Hamiltonicity, while general weighted TSP below remains open.
- Sums over subsets cost with the zeta transform, one pass per bit, instead of submask pairs; Möbius inversion undoes it, and subset convolution takes .
- Broken-profile DP scans a grid cell by cell with an -bit frontier: for domino tilings ( on a chessboard), and a transfer matrix handles huge lengths by fast powering.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
Held–Karp on cities: which pair of bounds is right?
- time, space
- time, space
- time, space
- time and polynomial space
Show the answer
B. time, space
There are entries, each a minimum over up to predecessors, and the whole table is kept. Polynomial space needs a different method, such as inclusion–exclusion (for Hamiltonicity, or for TSP with small integer distances).
Why may a bitmask DP simply loop over the masks in increasing order?
- Because the masks of equal popcount are consecutive
- Because adding an element to a set increases its integer value, so every set comes after all of its subsets
- Because each mask depends only on the mask just before it
- It may not; masks must be processed by increasing popcount
Show the answer
B. Because adding an element to a set increases its integer value, so every set comes after all of its subsets
A proper subset misses some bit of and has no bit outside , so its integer value is smaller. Transitions that add elements therefore always go to larger integers: increasing order is a topological order.
For every subset of items you need . Which method fits, and roughly how much work does it take?
- Enumerate the submasks of every mask: about steps
- The zeta transform, one pass per bit: about steps
- Subset convolution: about steps
- One step per pair of masks: steps
Show the answer
B. The zeta transform, one pass per bit: about steps
Each of the 20 passes touches the masks once: steps. Submask enumeration computes the same values in steps.
You count the domino tilings of a board with the broken-profile DP. What is the state, and about how much work does it take?
- One state per subset of the 1000 cells: hopeless
- A profile of 10 bits at each of the 1000 cell positions: at most states, each with at most two transitions
- A profile of 100 bits: states
- The number of dominoes placed so far: at most 500 states
Show the answer
B. A profile of 10 bits at each of the 1000 cell positions: at most states, each with at most two transitions
Scan so that each row runs along the short side: the profile then has bits, and the DP visits at most (profile, cell) pairs. With the board turned the other way the profile would need 100 bits.
Further reading
- M. Held & R. M. Karp, "A dynamic programming approach to sequencing problems," Journal of the Society for Industrial and Applied Mathematics 10(1) (1962), 196–210.
- R. M. Karp, "Dynamic programming meets the principle of inclusion and exclusion," Operations Research Letters 1(2) (1982), 49–51.
- A. Björklund, "Determinant sums for undirected Hamiltonicity," SIAM Journal on Computing 43(1) (2014), 280–299; FOCS 2010.
- A. Björklund, T. Husfeldt, P. Kaski & M. Koivisto, "Fourier meets Möbius: fast subset convolution," STOC 2007, 67–74.
- F. V. Fomin & D. Kratsch, Exact Exponential Algorithms (Springer, 2010).