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 answers.
Detailed Explanation
Permutations, subsets, n-queens, and Sudoku are search problems. The tree of partial assignments is huge. Backtracking explores one branch, and when a partial assignment already breaks a rule, it returns without generating the rest of that branch. That prune is the only reason the algorithm finishes.
The pattern is: choose, recurse, unchoose. You keep a mutable buffer (List<Integer> path) and a used-flags array. After the recursive call returns, you remove the last element so the next sibling sees the old state. Forgetting to undo is the usual bug: later branches inherit leftover choices.
Time is still exponential in the worst case. Pruning and symmetry cuts (start loops at start for subsets so {1,2} is not also {2,1}) are what make it usable. DP is better when you only need a count or an optimum and states overlap. Backtracking is what you want when you must list the solutions.
You reach for it when the output is a set of configurations and constraints can fail early. You reach for BFS when you want a shortest sequence of moves (sliding puzzle). You reach for greedy or DP when you do not need the actual list.
The cost in Java is allocation: creating a new ArrayList at every node is simpler and slower; mutating one list and copying it only when you record an answer (new ArrayList<>(path)) is the usual compromise. Recursion depth is the length of the path. Restore Thread stack concerns for n around 40+ on boolean arrays; n-queens at 9 is fine.
Index conventions: subsets use for (int i = start; i < n; i++). Permutations use used[i]. Combination-sum may reuse an index (i not i+1) when duplicates are allowed.
Code Examples
import java.util.ArrayList;
import java.util.List;
public class Subsets {
static void walk(int[] xs, int start, List<Integer> path, List<List<Integer>> out) {
out.add(new ArrayList<>(path)); // record a copy
for (int i = start; i < xs.length; i++) {
path.add(xs[i]);
walk(xs, i + 1, path, out);
path.remove(path.size() - 1); // undo
}
}
public static void main(String[] args) {
List<List<Integer>> out = new ArrayList<>();
walk(new int[] {1, 2}, 0, new ArrayList<>(), out);
System.out.println(out); // prints: [[], [1], [1, 2], [2]]
}
}import java.util.ArrayList;
import java.util.List;
public class Perms {
static void walk(int[] xs, boolean[] used, List<Integer> path, List<List<Integer>> out) {
if (path.size() == xs.length) {
out.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < xs.length; i++) {
if (used[i]) {
continue;
}
used[i] = true;
path.add(xs[i]);
walk(xs, used, path, out);
path.remove(path.size() - 1);
used[i] = false;
}
}
public static void main(String[] args) {
List<List<Integer>> out = new ArrayList<>();
walk(new int[] {1, 2}, new boolean[2], new ArrayList<>(), out);
System.out.println(out.size()); // prints: 2
}
}Common Gotchas
Forgetting to undo leaves `used` or `path` dirty
later siblings see the wrong state.
Storing `path` itself in the result shares one list
always `new ArrayList<>(path)`.
Subsets vs permutations
start-index vs used-flags. Mixing them duplicates or drops answers.
Exponential time is normal
prune early; do not expect O(n²) unless the tree is tiny.