E ExamMaster

Data Structures & Algorithms · Data Structures & Algorithms

DP for the Travelling Salesman

Held–Karp optimisation TSP: state (S, j) is the cheapest path from city 1 through exactly the cities in S ending at j, in O(n^2 2^n) — the shortest tour, not the NPC decision…

Five concepts on Held–Karp — optimisation TSP versus the NPC decision, the (S, j) state, the last-hop recurrence, the four-city fill that closes at 18, and O(n^2 2^n) versus (n-1)!. Same distances as branch and bound. Bellman–Ford already lives in graph algorithms; it is not repeated here.

  • Data Structures & Algorithms
  • Hard level
  • 5 concepts

1Shortest tour, not tour at most K

TSP-decision asks: is there a tour of cost at most K? That yes/no language is NP-complete; its certificate is a cyclic order. Optimisation TSP asks: what is the shortest tour? That question is NP-hard and is not a member of NP, because NP is a class of languages.

Held–Karp answers the optimisation question exactly, in exponential time. It does not decide a supplied K, and it is not a polynomial algorithm. The four-city instance whose decision answers are 'no' at K=17 and 'yes' at K=18 has optimisation answer 18.

Same 1-2-4-3-1 tour of cost 18. This concept only names the optimisation question whose answer is that 18.

Name the question

  1. DecisionTour \le K? Certificate = the order. NPC. Already taught.
  2. OptimisationShortest tour? NP-hard. This topic.
  3. Held–KarpExact DP for the second. Exponential, not a P-claim.
Same four cities, three questions
QuestionAnswer on this instance
Tour \le 17?No
Tour \le 18?Yes
Shortest tour?18
Held–Karp is an algorithm for
  1. Optimisation TSP — the shortest tour — in O(n^2 2^n) time
  2. TSP-decision in polynomial time, which would prove P = NP
  3. Approximating TSP within 1% on every instance

It returns the numeric optimum. It is exponential, so it is not a P = NP claim. It is exact, not an approximation scheme.

2State: the set visited and the city you end on

A permutation of n cities is too large to index a table. Held–Karp keeps only the set of cities already visited and the city the path currently ends at. Formally, g(S, j) is the cheapest path that starts at city 1, visits exactly the cities in S, and ends at j \in S. City 1 itself is left out of S.

Two paths that visited the same set and ended at the same j are interchangeable for every future completion. That is the optimal-substructure claim: you may forget the order inside the visited set except for the endpoint.

Figure. g(S, j) stores one number: cheapest path that started at 1, visited exactly the cities in S, and ended at j. City 1 stays outside S. The order inside S is forgotten.

Read one state

  1. SThe set of cities already visited, not including the start city 1.
  2. jWhere that path ended. j must sit in S.
  3. ValueA number — the cheapest such path — not a list of orders.

How many states on n = 4

Cities 1,2,3,4, start at 1. S ranges over nonempty subsets of {2,3,4}. How many pairs (S, j)?

  • subsets of size 13 states (one endpoint each)
  • subsets of size 23 \times 2 = 6 states
  • subsets of size 33 states
  • total12 — versus 3! = 6 tours, already more states than tours at n=4, fewer than (n-1)! once n grows

Pro tip. At n=4 the table is not smaller than listing tours. At n=20, 20^2 2^{20} is about 400 million; 19! is 1.2×10¹⁷.

The Held–Karp state (S, j) forgets
  1. The order of cities inside S other than the endpoint j
  2. The endpoint, keeping only the set
  3. The start city, which may be any element of S

The endpoint is part of the state. The start is fixed at city 1 and is excluded from S. Forgetting the endpoint would make the next edge undefined.

3Min over the city you arrived from

The cheapest path that visited S and ended at j arrived along one last edge i \to j with i \in S, i \neq j. The prefix that visited the smaller set and ended at the previous city must itself be cheapest, so g(S, j) = \min_{i \in S \setminus \{j\}} \bigl( g(S\setminus\{j\}, i) + d(i,j) \bigr).

The base is a single other city: g(\{j\}, j) = d(1, j). After every g(\{2,\ldots,n\}, j) is known, close the tour with the edge back to 1 and take the min.

Figure. g(S, j) is the min over previous endpoints i of g(S minus j, i) plus d(i, j). At |S|=2 there is one i: g({2,3},3) = g({2},2) + d(2,3) = 2+6=8. Larger S is the same min over more i.

One state from smaller sets

  1. Baseg(\{j\},j)=d(1,j).
  2. Grow SFor each j \in S, min over previous endpoints i.
  3. CloseOPT = \min_j g(\{2,\ldots,n\},j) + d(j,1).

Held–Karp (bitmask)

def held_karp(d):
    n = len(d)
    N = 1 << (n - 1)
    g = [[float('inf')] * n for _ in range(N)]
    for j in range(1, n):
        g[1 << (j - 1)][j] = d[0][j]
    for S in range(N):
        for j in range(1, n):
            if not (S & (1 << (j - 1))):
                continue
            prev = S ^ (1 << (j - 1))
            if prev == 0:
                continue
            g[S][j] = min(
                g[prev][i] + d[i][j]
                for i in range(1, n)
                if prev & (1 << (i - 1))
            )
    full = N - 1
    return min(g[full][j] + d[j][0] for j in range(1, n))

One size-2 cell

d(1,2)=2, d(2,3)=6. What is g({2,3}, 3)?

  • only previous i in {2}i = 2
  • g(\{2\},2) + d(2,3)2 + 6 = 8
  • g(\{2,3\},3)8 — path 1-2-3

Pro tip. There is only one i because |S|=2. Size 3 is where a real min over two predecessors appears.

g(S,j) takes a min over
  1. Previous endpoints i \in S, i \neq j, of g(S\setminus\{j\},i)+d(i,j)
  2. All permutations of S
  3. All unused cities, including city 1

The recurrence enumerates the last hop, not the full permutation. City 1 is the global start and is not a previous endpoint inside S.

4Twelve states on the four-city instance close at 18

Distances: 1{-}2=2, 1{-}3=9, 1{-}4=10, 2{-}3=6, 2{-}4=4, 3{-}4=3. Base: g(\{2\},2)=2, g(\{3\},3)=9, g(\{4\},4)=10.

Size 3: g(\{2,3,4\},2)=16, g(\{2,3,4\},3)=9, g(\{2,3,4\},4)=11. Closing: 16+d(2,1)=18, 9+d(3,1)=18, 11+d(4,1)=21. Optimum 18.

Figure. Tour 1-2-4-3-1, edges 2+4+3+9=18. This is g({2,3,4},3)+d(3,1). The sibling 1-3-4-2-1 also costs 18.

Size-3 cells from size-2

  1. End at 2\min(g(\{3,4\},3)+6,\, g(\{3,4\},4)+4) = \min(13+6,\,12+4)=16.
  2. End at 3\min(g(\{2,4\},2)+6,\, g(\{2,4\},4)+3) = \min(14+6,\,6+3)=9.
  3. End at 4\min(g(\{2,3\},2)+4,\, g(\{2,3\},3)+3) = \min(15+4,\,8+3)=11.
Size-2 cells used above
StateValuePath
g(\{2,3\},2)151-3-2
g(\{2,3\},3)81-2-3
g(\{2,4\},2)141-4-2
g(\{2,4\},4)61-2-4
g(\{3,4\},3)131-4-3
g(\{3,4\},4)121-3-4

Close the three full-set states

Add the return edge to city 1 from each full-set endpoint.

  • g(\{2,3,4\},2)+d(2,1)16+2=18
  • g(\{2,3,4\},3)+d(3,1)9+9=18
  • g(\{2,3,4\},4)+d(4,1)11+10=21
  • OPT18

Pro tip. g({2,3,4},3)=9 is the path 1-2-4-3 (edges 2+4+3). Adding 9 returns the tour of cost 18 already named in branch and bound.

Coding lab. Held-Karp on four cities runs in the app, with checks on your output.

On this instance g(\{2,3,4\},3)+d(3,1) equals
  1. 18 — one of the two optimal closings
  2. 9 — the state without the return edge, reported as the tour
  3. 21 — the closing through city 4

The state is 9; the tour adds d(3,1)=9. 21 is the closing through 4. Forgetting the return edge is the usual off-by-the-last-edge error.

5O(n² 2ⁿ) is smaller than n! and still exponential

There are O(n 2^{n}) states and each takes a min over O(n) predecessors, so the fill is O(n^2 2^n). Enumerating tours from a fixed start is (n-1)!. For n \ge 8 the factorial has already pulled away; for n=20 Held–Karp is in the hundreds of millions of states and 19! is not enumerable.

That is still exponential. NP-completeness of the decision problem is not contradicted. Branch and bound on the same instance may expand fewer nodes if the bound is strong; Held–Karp always fills the table. Use Held–Karp when you want a simple exact n \le 15 solver; use B&B when a bound can kill most of the tree.

No bar chart of 19! — that value cannot be drawn on a linear axis next to 2^20. The three-row table is the comparison.

n = 4 versus the idea of n = 20
Methodn = 4Growth
Tours (n-1)!619! \approx 1.2 \times 10^{17}
Held–Karp states12O(n 2^{n}) \approx 20 \cdot 2^{20}
Held–Karp timeO(n^2 2^n)hundreds of millions of updates

4! / 2 versus 4² 2⁴

Compare (n-1)! with n² 2^n at n=4 and the ratio of those two closed forms at n=8 (order of magnitude).

  • (4-1)!6
  • 4^2 \cdot 2^416 · 16 = 256 (loose upper bound on work)
  • (8-1)!5040
  • 8^2 \cdot 2^864 · 256 = 16384 — same order; the factorial then pulls away

Pro tip. The n=4 table is not why anyone quotes Held–Karp. The n=15 table is. Do not read 256 versus 6 as 'DP is slower' — the 256 is a crude n^2 2^n ceiling, and the 12 states were the real fill.

Held–Karp versus listing tours is
  1. Asymptotically better than (n-1)!, still exponential, not a polynomial TSP algorithm
  2. Polynomial, which is why TSP is in P
  3. Worse than (n-1)! for every n, so it is only a teaching device

The 2^n beats the factorial and does not beat every polynomial. At n=4 the constant-factor story is noisy; at n=20 it is not.

Notes

  • Optimisation TSP asks for a shortest tour, not whether a tour of cost at most K exists. The decision version is NP-complete; the optimisation version is NP-hard. Held–Karp is an exact exponential algorithm for the second.
  • State: g(S, j) = cheapest path that starts at city 1, visits exactly the cities in S, and ends at j ∈ S. City 1 is excluded from S.
  • Base: g({j}, j) = d(1, j). Recurrence: g(S, j) = min_{i ∈ S, i ≠ j} g(S \ {j}, i) + d(i, j).
  • Optimum tour = min_j g({2,\ldots,n}, j) + d(j, 1). Time O(n^2 2^n), space O(n 2^n).
  • The four-city instance from branch and bound (shortest tour 18) is the running example. Held–Karp finds 18 by filling 12 useful states, not by listing 6 tours.

Formulas

  • g(\{j\}, j) = d(1,j) for j \neq 1.
  • g(S,j) = \min_{i \in S \setminus \{j\}} \bigl( g(S\setminus\{j\}, i) + d(i,j) \bigr).
  • OPT = \min_j \bigl( g(\{2,\ldots,n\}, j) + d(j,1) \bigr).
  • States: n \cdot 2^{n-1} (subsets of the other n-1 cities, times an endpoint).
  • Time O(n^2 2^n) versus (n-1)! enumerated tours.

Exam traps & shortcuts

  • Do not quote Held–Karp as a polynomial TSP algorithm. 2^n is exponential. It is the exact method the NPC topic already named as legal for small n.
  • The state is a set plus an endpoint, not a permutation. That is why 12 states beat 6 listed tours on n=4 and why 20 cities are still hopeless.
  • Branch and bound on the same instance also finds 18. Held–Karp always fills every state; B&B hopes a bound prunes. They are not the same algorithm.
  • A yes/no for a budget K is TSP-decision. This topic returns the number 18.

Reference tables

Symmetric. Diagonal unused.

Distance matrix
1234
12910
2264
3963
41043

Full set {2,3,4}.

Closing the tour
End jg(full, j)d(j,1)Tour cost
216218
39918
4111021

Recap

Night-before Held–Karp pegs.

Question
Shortest tour (NP-hard), not tour \le K (NPC).
State
g(S,j): start at 1, visit S, end at j. Forget the order inside S.
Recurrence
g(S,j)=\min_i g(S\setminus\{j\},i)+d(i,j). Close with +d(j,1).
18
This instance: two optimal closings at 18, one at 21.
Time
O(n^2 2^n). Better than n!, still exponential.

Practise DP for the Travelling Salesman

Reading is free and needs no account. Practice, mocks and progress live in the app.

  • A 5-question practice set that ends the chapter
  • 5 quick checks with worked explanations
  • Timed mocks scored with the real marking scheme
  • Readiness tracked per topic, kept on your device
Continue with Google — freeNo card, no trial. Works offline once installed.