Home/Data Structures & Algorithms/Advanced DP: Bitmask & Tree DP

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Bitmask TSP, Digit DP, Tree rerooting, broken-profile domino tilings, and matrix exponentiation.
Traveling Salesperson Problem: How does Bitmask DP reduce (N – 1)! factorial to O(N^2 * 2^N)?
The Held-Karp Bitmask DP algorithm is the premier textbook demonstration of converting a factorial combinatorial explosion into a manageable exponential dynamic programming state space. 1. The Core Insight (Subproblem Overlap) Suppose a drone visits cities in the order: 1 → 2 → 3 → 4.Read more
The Held-Karp Bitmask DP algorithm is the premier textbook demonstration of converting a factorial combinatorial explosion into a manageable exponential dynamic programming state space.
1. The Core Insight (Subproblem Overlap)
Suppose a drone visits cities in the order:
1 → 2 → 3 → 4.Another candidate path visits cities in the order:
1 → 3 → 2 → 4.Notice that in both cases, the set of visited cities is identical ({1, 2, 3, 4}), and the current ending city is identical (City 4)!
For future route choices (visiting the remaining cities 5 through 20), it does not matter how you traveled between 1, 2, and 3—all that matters is what is the minimum cost to have visited that exact subset and currently be sitting at City 4!
2. The State Definition
We define our DP state with two parameters:
dp(mask, u)mask: An integer whose binary bits represent the subset of visited cities. If bitiis1, Cityihas been visited. If bitiis0, Cityiis unvisited.u: The current city where the drone is currently parked.Transition:
To move to an unvisited city
v(where(mask & (1 << v)) == 0):Clean Python 3.12 Implementation with Memoization
Complexity Breakdown: From 10^17 down to 10^7
For $N = 20$:
- Brute force $19! pprox 1.21 imes 10^{17}$ operations (would take 3,800 years at 1 GHz).
- Held-Karp $20^2 cdot 2^{20} = 400 imes 1,048,576 pprox 4.19 imes 10^8$ operations (runs in under 1.5 seconds on a modern CPU)!
See less