Backtracking
Backtracking builds a solution one choice at a time and undoes a choice when it cannot lead to a valid answer. It is depth-first search on an implicit tree of partial solutions.
Detailed Explanation
When the problem is "list every permutation", "place N queens", "find all subsets that sum to target", there is no closed formula you want to write. You grow a path of decisions. If the path is already illegal (two queens share a diagonal, the sum already exceeds the target), you stop that branch. If the path is a complete solution, you record a copy. Then you undo the last decision and try the next option.
The undo is the name. path.push(x); explore(); path.pop(); The pop (or used[i] = false, or board[r][c] = '.') puts the shared state back so the sibling choice sees a clean board. Forgetting the undo is the first bug. Recording path without copying it is the second: every stored answer aliases the same array, which is empty at the end.
Pruning is what makes backtracking finish. Order the choices so failures happen early. Skip duplicates (if (i > start && nums[i] === nums[i - 1]) continue on a sorted list). Bound the remaining sum. Do not generate symmetric boards if the problem does not want them.
Complexity is often exponential. n! permutations, 2^n subsets. n = 10 is fine. n = 20 needs pruning or a different algorithm. If you only need a count or a yes/no, DP or bitmasks may be O(n 2^n) with a better constant, or polynomial.
JavaScript recursion depth follows the path length, usually n, which is safe. The time is the problem. Prefer generating functions that yield solutions if the caller might stop early.
What it costs you: time, and mutable-state bugs. A version that passes a new array (explore([...path, x])) avoids pop at the cost of O(n) copies per node. That is simpler and often fast enough.
Reach for backtracking when you must enumerate or search a combinatorial space. Reach for DP when you count or optimise over that space. Reach for greedy when a single constructive pass is proven enough.
Code Examples
function permutations(items) {
const out = [];
const used = new Array(items.length).fill(false);
const path = [];
function walk() {
if (path.length === items.length) {
out.push([...path]); // copy
return;
}
for (let i = 0; i < items.length; i += 1) {
if (used[i]) continue;
used[i] = true;
path.push(items[i]);
walk();
path.pop();
used[i] = false;
}
}
walk();
return out;
}
console.log(permutations([1, 2]));
// => [ [ 1, 2 ], [ 2, 1 ] ]function subsets(nums) {
const out = [];
function walk(start, path) {
out.push([...path]);
for (let i = start; i < nums.length; i += 1) {
path.push(nums[i]);
walk(i + 1, path);
path.pop();
}
}
walk(0, []);
return out;
}
console.log(subsets([1, 2]));
// => [ [], [ 1 ], [ 1, 2 ], [ 2 ] ]Common Gotchas
Pushing `path` itself into `out` stores a live alias
clone with `[...path]` when you record a solution.
Forgetting `pop` / unmark poisons later branches
pair every mutate with an undo, preferably adjacent in the source.
Duplicate inputs generate duplicate solutions
sort and skip runs, or use a `Set` of serialised paths if n is tiny.
Exponential time is expected
if n grows, change the problem (count via DP) or prune harder.