Dynamic Programming21 sections · 916 units
Open in Course

TSP - Transition

Add next city

From state (mask,last)(\text{mask}, \text{last}), try going to any unvisited city next\text{next}. Check if next is unvisited: (mask>>next)1=0(\text{mask} >> \text{next}) \land 1 = 0.

If so, transition to (mask(1<<next),next)(\text{mask} \mid (1 << \text{next}), \text{next}) with added cost cost[last][next]\text{cost}[\text{last}][\text{next}]. Process masks in increasing order. Smaller subsets (fewer bits set) must be computed before larger ones, since you build up by adding cities.

This topological order keeps dependencies are satisfied. For each mask, try all nn possible last cities and all nn possible next cities. That's O(n2)O(n^2) work per mask, giving O(n22n)O(n^2 \cdot 2^n) total.