DSA · Intermediate · Pattern 6 of 10
Backtracking
14 problems.
Your progress0%
- 1st Visit
- 0/14
- 2nd Visit
- 0/14
- Revise
- 0/14
About this pattern
Backtracking builds candidate solutions one choice at a time and abandons a partial candidate as soon as it cannot lead to a valid answer. It is a depth-first search over the tree of decisions: choose, recurse, then undo the choice so the next option starts from a clean state.
Use it when the statement asks for all subsets, permutations, combinations or arrangements, or for any assignment that satisfies a set of constraints, and the input is small (often n at most 15 to 20). The worst case is exponential, such as O(2^n) or O(n!), so pruning invalid branches early is what makes these solutions fast in practice.
vector<vector<int>> result;
vector<int> path;
void backtrack(int start, const vector<int>& a) {
result.push_back(path); // record current candidate
for (int i = start; i < (int)a.size(); ++i) {
if (!canUse(i)) continue; // prune
path.push_back(a[i]); // choose
backtrack(i + 1, a); // explore
path.pop_back(); // undo
}
}