Travelling Salesman (bitmask DP)
Problem Statement
You have n cities numbered 0 to n − 1. cost[i][j] is the price of travelling directly from city i to city j. The two directions can have different prices.
Start at city 0. Visit every other city exactly once, then come back to city 0. Return the smallest total cost of such a tour.
With only one city there is no trip to make, so the answer is 0.
A square matrix cost of size n × n.
One integer: the least total cost of a tour that starts at city 0, visits each city once, and returns to city 0. The function is int tsp(vector<vector<int>>& cost).
There are only two cities. The tour 0 → 1 → 0 costs 111 + 112 = 223.
The tour 0 → 1 → 2 → 0 costs 1000 + 1000 + 1000 = 3000. The other way round, 0 → 2 → 1 → 0, costs 15000.
- • 1 ≤ n ≤ 15
- • 0 ≤ cost[i][j] ≤ 10^4
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Try all (n − 1)! orders of cities 1 … n−1 and add the trip back to 0
dp[mask][last] = cheapest walk from 0 that visits mask and ends at last; extend by one city
A tour is city 0, then some order of the other cities, then back to 0. Write every order with next_permutation, add up the cost of each tour, and keep the smallest. There are (n − 1)! orders, so this only works for small n.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Bit Manipulation translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.