Backtracking
Backtracking is a depth-first search over a tree of partial solutions. You add a choice, recurse, then undo the choice so the next sibling can try a different one. Pruning skips branches that cannot beat the constraints.
Detailed Explanation
Permutations, combinations, N-queens, Sudoku, subset-sum: the solution is a sequence of decisions. At each index you try a legal next item, recurse to the next index, then pop the item. The data structure that holds the partial answer is shared; undo is what makes the share safe.
The skeleton:
void search() {
if (done()) { record(); return; }
for (choice : options) {
if (!legal(choice)) continue;
apply(choice);
search();
undo(choice);
}
}
legal is the prune. If a queen already attacks this square, do not recurse. If the remaining capacity is negative, do not recurse. Pruning is the difference between n! and something you can finish.
C++ details. Store the partial solution in a vector you push_back / pop_back. Store used flags in a vector<char> (not vector<bool>). Pass n and the original input by const&. Copy the vector into the answer list when you hit a complete solution (ans.push_back(path)), or the later undos will empty what you stored.
Time is exponential in the worst case. You document it as O(b^d) for branching factor b and depth d, times the cost of legal. Space is O(d) for the path plus whatever legal needs.
Backtracking versus DP: if subproblems overlap and you only need a count or an optimum, DP stores them. If you need every concrete solution (all permutations), backtracking enumerates them. Versus BFS: BFS would store every partial path of a given length; the queue is huge. DFS backtracking stores one path.
Iterative backtracking uses an explicit stack of frames (index, next choice). Recursion is clearer until depth is thousands.
Bitsets (std::bitset or an unsigned mask) speed N-queens and subset problems for n ≤ 20–64. mask & (1u << i) tests, mask ^ (1u << i) toggles.
Code Examples
#include <cstddef>
#include <iostream>
#include <vector>
void permute(std::vector<int>& nums, std::vector<char>& used,
std::vector<int>& path, std::vector<std::vector<int>>& out) {
if (path.size() == nums.size()) {
out.push_back(path); // copy; path will be undone
return;
}
for (std::size_t i = 0; i < nums.size(); ++i) {
if (used[i]) continue;
used[i] = 1;
path.push_back(nums[i]);
permute(nums, used, path, out);
path.pop_back();
used[i] = 0;
}
}
int main() {
std::vector<int> nums{1, 2};
std::vector<char> used(2);
std::vector<int> path;
std::vector<std::vector<int>> out;
permute(nums, used, path, out);
std::cout << out.size() << '\n'; // prints: 2
}#include <vector>
void subsets(int i, const std::vector<int>& nums,
std::vector<int>& path, std::vector<std::vector<int>>& out) {
if (i == static_cast<int>(nums.size())) {
out.push_back(path);
return;
}
subsets(i + 1, nums, path, out); // skip nums[i]
path.push_back(nums[static_cast<std::size_t>(i)]);
subsets(i + 1, nums, path, out); // take nums[i]
path.pop_back();
}Common Gotchas
Storing a reference to `path` in the answers
every answer then aliases the same vector, which is empty at the end. Copy.
Forgetting undo
the next sibling sees leftover used-flags or an extra element. Every `apply` has a matching `undo` on the same function-exit path, including after `continue`.
`vector<bool>` as `used` is not a real container
`used[i] = 1` is a proxy. Use `vector<char>` or `vector<int>`.
Duplicate elements
permutations of `{1, 1, 2}` need a skip rule (`if (i && nums[i]==nums[i-1] && !used[i-1])`) after sorting, or you emit duplicates.