Video in progress

Strong Middle 🧠 Problem solving

What is pruning in backtracking? Show it with finding combinations that sum to a target.

Backtracking means making a choice, recursing, and undoing the choice on the way back. Pruning means cutting a branch early when it's clear it can't lead to an answer. For example, in a sorted array, if an element is larger than the remaining target, we don't bother trying the ones after it.

📖 Answer

The problem: given positive numbers, find all unique combinations that sum to target, using each number at most once.

static List<List<Integer>> combinationSum(int[] nums, int target) {
    Arrays.sort(nums);
    List<List<Integer>> res = new ArrayList<>();
    dfs(nums, 0, target, new ArrayList<>(), res);
    return res;
}

static void dfs(int[] a, int start, int left, List<Integer> path, List<List<Integer>> res) {
    if (left == 0) { res.add(new ArrayList<>(path)); return; }
    for (int i = start; i < a.length; i++) {
        if (i > start && a[i] == a[i - 1]) continue;  // cut duplicate combinations
        if (a[i] > left) break;                       // pruning: the next ones are even larger
        path.add(a[i]);
        dfs(a, i + 1, left - a[i], path, res);
        path.remove(path.size() - 1);                 // undo the choice
    }
}

There are two cuts here. The break works thanks to the sorting; without sorting you could only continue, and the tree would be much bigger. The duplicate check is there so that [1,2] isn't produced twice from [1,1,2].

res.add(new ArrayList<>(path)) must make a copy. If you add path itself, at the end every result turns into the same empty list. This bug is very common in interviews.

The worst-case complexity is exponential, O(2ⁿ). Pruning doesn't change the asymptotics, but in practice it speeds things up by several orders of magnitude. N-Queens works the same way: you keep the occupied columns and diagonals in a boolean[] and never step into an attacked cell at all.