Traveling Salesperson DP
Use a bitmask for visited cities and end-position states to assemble the shortest Hamiltonian tour.
Core idea
State dp[mask][i] stores the shortest path that starts at city zero, visits exactly the mask, and ends at i. Remove i to enumerate the predecessor of the final edge.
Read the visualization
Rows decode visited-city bitmasks and columns choose the endpoint. Each filled cell highlights predecessor states, and the closing phase adds one edge back to the start.
| 0 | 1 | 2 | 3 | |
|---|---|---|---|---|
| 0001 | 0 | |||
| 0011 | ||||
| 0101 | ||||
| 0111 | ||||
| 1001 | ||||
| 1011 | ||||
| 1101 | ||||
| 1111 |
Start at city zero with only its bit set and zero path cost.
Complexity and tradeoffs
Time: O(n^2 2^n). Space: O(n 2^n). Held-Karp is exponential but far smaller than checking all n! tours.
Where it fits
Held-Karp is practical only for small city counts, but its bitmask-state technique is central to subset scheduling, assignment, and visit-all-nodes problems.