Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

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 19!/2≈6×101619!/2\approx6\times10^{16} 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: 219⋅19≈1072^{19}\cdot19\approx10^7 states. More than sixty years later, no algorithm for the general traveling salesman problem is known to beat 2n2^n by an exponential factor.

What you’ll learn

  • State and prove the Held–Karp recurrence, count its entries, (n−1)2n−2(n-1)2^{n-2}, and its time, Θ(2nn2)\Theta(2^nn^2), and reconstruct an optimal tour.
  • Count Hamiltonian cycles in O∗(2n)O^*(2^n) time and polynomial space by inclusion–exclusion, and describe what is known below 2n2^n.
  • Compute sums over subsets in O(2nn)O(2^nn) with the zeta transform instead of 3n3^n, and state the O(2nn2)O(2^nn^2) subset convolution.
  • Count tilings with broken-profile DP in O(nm 2m)O(nm\,2^m), and connect it to transfer matrices and Kasteleyn's formula.

Held–Karp, precisely

DerivationProof and cost
  1. dp[S][j]=min⁡k∈S∖{j}(dp[S∖{j}][k]+d(k,j))\mathrm{dp}[S][j]=\min_{k\in S\setminus\{j\}}\big(\mathrm{dp}[S\setminus\{j\}][k]+d(k,j)\big)

    Optimal substructure. In a shortest such path to jj with ∣S∣≥2\abs S\ge2, let kk be the city before jj. The part before kk is a path from 0 through exactly S∖{j}S\setminus\{j\} ending at kk; if a shorter one existed, splicing it in would shorten the whole path (cut and paste). Conversely, every kk and every such path extends by the edge kjkj. Hence the minimum over kk.

  2. #{(S,j): j∈S}=(n−1) 2n−2\#\{(S,j):\ j\in S\}=(n-1)\,2^{n-2}

    Entries. Each of the n−1n-1 cities jj lies in 2n−22^{n-2} subsets of {1,…,n−1}\{1,\dots,n-1\}:

  3. (n−1)(n−2) 2n−3+(n−1)=Θ(2nn2),space Θ(2nn)(n-1)(n-2)\,2^{n-3}+(n-1)=\Theta(2^nn^2),\qquad \text{space }\Theta(2^nn)

    Sums compared. The entry (S,j)(S,j) compares ∣S∣−1\abs S-1 candidates, and summing over the sizes of SS gives (n−2)2n−3(n-2)2^{n-3} per city jj; closing the tour adds n−1n-1 more:

  4. S⊊T ⟹ ∑i∈S2i<∑i∈T2iS\subsetneq T\ \Longrightarrow\ \textstyle\sum_{i\in S}2^i<\sum_{i\in T}2^i

    Reconstruction. Store the minimizing kk with each entry, or recompute it, and walk back from the best final jj: O(n2)O(n^2) more time. Masks in increasing integer order list every set after its subsets, so a single loop over masks is a valid order.

Predict before you look

How many table entries dp[S][j]\mathrm{dp}[S][j] does Held–Karp fill for n=12n=12 cities?

Show the answer

11264

(n−1) 2n−2=11⋅210=11,264(n-1)\,2^{n-2}=11\cdot2^{10}=11{,}264, against 11!/2=19,958,40011!/2=19{,}958{,}400 tours for brute force. Each extra city roughly doubles the table, while brute force multiplies its work by nn.

Below 2ⁿ, and in polynomial space

Held–Karp's weakness is memory: for n=30n=30 the table has 29⋅228≈7.8×10929\cdot2^{28}\approx7.8\times10^9 entries. For the decision version, "is there a Hamiltonian cycle?", counting is the way out. Let W(H)W(H) be the number of closed walks of length nn from vertex 0 that use only the vertices of HH: easy to count by a DP over the walk's length, in polynomial time and space. A closed walk of length nn from 0 that visits all nn 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):

#{Hamiltonian cycles through 0, directed}=∑X⊆V∖{0}(−1)∣X∣ W(G−X).\#\{\text{Hamiltonian cycles through 0, directed}\}=\sum_{X\subseteq V\setminus\{0\}}(-1)^{\abs X}\,W(G-X).

That is 2n−12^{n-1} polynomial-time counts: O∗(2n)O^*(2^n) time and polynomial space.

Check your understanding

A closed walk of length nn from vertex 0 misses exactly the vertices of a non-empty set MM. How much does it contribute in total to the inclusion–exclusion sum?

  1. +1+1
  2. (−1)∣M∣(-1)^{\abs M}
  3. 00
  4. 2∣M∣2^{\abs M}
Show the answer

C. 00

It is counted in W(G−X)W(G-X) exactly for the sets X⊆MX\subseteq M, with sign (−1)∣X∣(-1)^{\abs X}, and ∑X⊆M(−1)∣X∣=(1−1)∣M∣=0\sum_{X\subseteq M}(-1)^{\abs X}=(1-1)^{\abs M}=0 for non-empty MM. Only walks that miss nothing, the Hamiltonian cycles, survive, each counted once (for X=∅X=\emptyset).

Beating 2n2^n. For undirected graphs, Björklund (FOCS 2010; SIAM J. Comput. 2014) decides Hamiltonicity in O∗(1.657n)O^*(1.657^n) randomized time by summing determinants over a field of characteristic two, and in O∗(1.415n)O^*(1.415^n) on bipartite graphs. For the traveling salesman with weights, Nederlof (STOC 2020) solved bipartite instances in O(1.9999n)O(1.9999^n) randomized time, assuming matrix multiplication takes essentially quadratic time. For general weighted TSP nothing of the form O((2−ε)n)O((2-\varepsilon)^n) is known; a 2024 preprint by Stoian removes only a subexponential factor, reaching 2nn2/2Ω(log⁡n)2^nn^2/2^{\Omega(\sqrt{\log n})} through fast (min⁡,+)(\min,+) products.

Sums over subsets

Many bitmask DPs need, for every set SS, an aggregate over all of its subsets: f(S)=∑T⊆Sg(T)f(S)=\sum_{T\subseteq S}g(T), the zeta transform of gg, known in contests as sum over subsets (SOS DP). Enumerating the submasks of every mask costs ∑S2∣S∣=3n\sum_S2^{\abs S}=3^n steps. Adding one bit at a time costs O(2nn)O(2^nn).

DerivationThe zeta transform in O(2ⁿ n)
  1. fi(S)=∑T⊆ST∩{i,…,n−1}=S∩{i,…,n−1}g(T),f0=gf_i(S)=\sum_{\substack{T\subseteq S\\ T\cap\{i,\dots,n-1\}\,=\,S\cap\{i,\dots,n-1\}}} g(T),\qquad f_0=g

    Process the bits one at a time. Invariant: after bits 0,…,i−10,\dots,i-1 have been processed, fi(S)f_i(S) sums g(T)g(T) over the subsets T⊆ST\subseteq S that agree with SS on the bits i,…,n−1i,\dots,n-1:

  2. fi+1(S)={fi(S)+fi(S∖{i})if i∈S,fi(S)otherwise.f_{i+1}(S)=\begin{cases}f_i(S)+f_i\big(S\setminus\{i\}\big) & \text{if } i\in S,\\ f_i(S) & \text{otherwise.}\end{cases}

    Processing bit ii: if SS contains bit ii, its subsets may now also lack bit ii, and those are exactly the subsets counted by fi(S∖{i})f_i(S\setminus\{i\}):

  3. O(2nn) instead of 3n:n=20: 2.1×107 versus 3.5×109O(2^nn)\ \text{instead of}\ 3^n:\qquad n=20:\ 2.1\times10^7\ \text{versus}\ 3.5\times10^9

    After all nn bits, fn(S)=∑T⊆Sg(T)f_n(S)=\sum_{T\subseteq S}g(T), at one pass over the 2n2^n masks per bit. Subtracting instead of adding undoes the passes, which is Möbius inversion, g(S)=∑T⊆S(−1)∣S∖T∣f(T)g(S)=\sum_{T\subseteq S}(-1)^{\abs{S\setminus T}}f(T):

python
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 f

Checked against direct summation over all submasks for n≤8n\le8. 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, h(S)=∑T⊆Sf(T) g(S∖T)h(S)=\sum_{T\subseteq S}f(T)\,g(S\setminus T), which splits SS into two disjoint parts; done directly it costs 3n3^n again. Björklund, Husfeldt, Kaski and Koivisto (STOC 2007) computed it with O(2nn2)O(2^nn^2) 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 n×mn\times m board with 1×21\times2 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 mm cells are already covered by dominoes sticking out of the filled part: a mask of mm 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.

python
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))     # 12988816

At most 2m2^m profiles per cell and at most two transitions each: O(nm 2m)O(nm\,2^m) time, with mm the shorter side. On the 8×88\times8 board at most 70 profiles are reachable at any one time.

Think first How many domino tilings does a 2×102\times10 board have?
  1. The leftmost column is covered either by one vertical domino, leaving a 2×92\times9 board, or by two horizontal ones, leaving 2×82\times8. So T(10)=T(9)+T(8)T(10)=T(9)+T(8) with T(1)=1T(1)=1 and T(2)=2T(2)=2: the Fibonacci numbers 1,2,3,5,8,13,21,34,55,891,2,3,5,8,13,21,34,55,89. The profile DP returns 89 too.

Transfer matrices. Processed a whole row at a time, the same DP is a 2m×2m2^m\times2^m matrix MM whose entry M[a][b]M[a][b] counts the ways to fill one row when profile aa comes in and profile bb goes out, and the number of tilings is (Mn)[0][0](M^n)[0][0]. For a fixed width and a huge length nn, fast matrix powering computes it with O(8mlog⁡n)O(8^m\log n) arithmetic operations (see Linear Recurrences & Matrix Powers). Statistical physicists call this the transfer-matrix method.

Key takeaways

  • Held–Karp: dp[S][j]=min⁡k(dp[S∖{j}][k]+d(k,j))\mathrm{dp}[S][j]=\min_k\big(\mathrm{dp}[S\setminus\{j\}][k]+d(k,j)\big), with (n−1)2n−2(n-1)2^{n-2} entries, Θ(2nn2)\Theta(2^nn^2) time and Θ(2nn)\Theta(2^nn) space; integer order of masks is a topological order.
  • Inclusion–exclusion over closed walks counts Hamiltonian cycles in O∗(2n)O^*(2^n) time and polynomial space; Björklund's O∗(1.657n)O^*(1.657^n) beats 2n2^n for undirected Hamiltonicity, while general weighted TSP below 2n2^n remains open.
  • Sums over subsets cost O(2nn)O(2^nn) with the zeta transform, one pass per bit, instead of 3n3^n submask pairs; Möbius inversion undoes it, and subset convolution takes O(2nn2)O(2^nn^2).
  • Broken-profile DP scans a grid cell by cell with an mm-bit frontier: O(nm 2m)O(nm\,2^m) for domino tilings (12,988,81612{,}988{,}816 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.

Question 1

Held–Karp on nn cities: which pair of bounds is right?

  1. Θ(n!)\Theta(n!) time, Θ(n)\Theta(n) space
  2. Θ(2nn2)\Theta(2^nn^2) time, Θ(2nn)\Theta(2^nn) space
  3. Θ(2n)\Theta(2^n) time, Θ(n2)\Theta(n^2) space
  4. Θ(n22n)\Theta(n^22^n) time and polynomial space
Show the answer

B. Θ(2nn2)\Theta(2^nn^2) time, Θ(2nn)\Theta(2^nn) space

There are (n−1)2n−2(n-1)2^{n-2} entries, each a minimum over up to n−2n-2 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).

Question 2

Why may a bitmask DP simply loop over the masks 0,1,2,…,2n−10,1,2,\dots,2^n-1 in increasing order?

  1. Because the masks of equal popcount are consecutive
  2. Because adding an element to a set increases its integer value, so every set comes after all of its subsets
  3. Because each mask depends only on the mask just before it
  4. 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 S⊊TS\subsetneq T misses some bit of TT and has no bit outside TT, so its integer value is smaller. Transitions that add elements therefore always go to larger integers: increasing order is a topological order.

Question 3

For every subset SS of n=20n=20 items you need f(S)=∑T⊆Sg(T)f(S)=\sum_{T\subseteq S}g(T). Which method fits, and roughly how much work does it take?

  1. Enumerate the submasks of every mask: about 3.5×1093.5\times10^9 steps
  2. The zeta transform, one pass per bit: about 2×1072\times10^7 steps
  3. Subset convolution: about 4×1084\times10^8 steps
  4. One step per pair of masks: 420≈10124^{20}\approx10^{12} steps
Show the answer

B. The zeta transform, one pass per bit: about 2×1072\times10^7 steps

Each of the 20 passes touches the 2202^{20} masks once: 20⋅220≈2.1×10720\cdot2^{20}\approx2.1\times10^7 steps. Submask enumeration computes the same values in 320≈3.5×1093^{20}\approx3.5\times10^9 steps.

Question 4

You count the domino tilings of a 10×10010\times100 board with the broken-profile DP. What is the state, and about how much work does it take?

  1. One state per subset of the 1000 cells: hopeless
  2. A profile of 10 bits at each of the 1000 cell positions: at most 1000⋅210≈1061000\cdot2^{10}\approx10^6 states, each with at most two transitions
  3. A profile of 100 bits: 21002^{100} states
  4. 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 1000⋅210≈1061000\cdot2^{10}\approx10^6 states, each with at most two transitions

Scan so that each row runs along the short side: the profile then has m=10m=10 bits, and the DP visits at most nm 2m=1000⋅1024≈106nm\,2^m=1000\cdot1024\approx10^6 (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).