Subsets & Backtracking

One template for subsets, permutations, combinations, partitions and constraint puzzles — choose, explore, un-choose.

Intermediate 2 min readLesson 20 of 25

Problems that ask for all solutions (every subset, every permutation, every valid board) are solved by backtracking: build a candidate one choice at a time, recurse, then undo the choice and try the next one. (Theory and pruning: Backtracking.)

[1,2,3][1,2][1,3][1][2,3][2][3][ ]
Subsets of [1,2,3]: every node in the recursion tree is one answer.
When to use this pattern
  • "Return all subsets / permutations / combinations / partitions."
  • "Generate every valid…" (parentheses, IP addresses, palindrome partitions).
  • Constraint puzzles: N-Queens, Sudoku, word search.
  • n is small (around 20 or fewer): exponential output is expected.

The universal template

backtrack(state, choices):
    if state is a complete answer: record a copy
    for each choice still available:
        if choice is invalid: skip            ← pruning
        make the choice
        backtrack(next state)
        undo the choice                       ← the "back" in backtracking

Subsets, combinations, permutations

// Subsets: every node is an answer; 'start' prevents reusing earlier elements.
void subsets(int[] a, int start, List<Integer> cur, List<List<Integer>> res) {
    res.add(new ArrayList<>(cur));
    for (int i = start; i < a.length; i++) {
        cur.add(a[i]);
        subsets(a, i + 1, cur, res);
        cur.remove(cur.size() - 1);
    }
}

// Combination sum (reuse allowed → recurse with i, not i + 1). 'a' must be sorted.
void combo(int[] a, int start, int remain, List<Integer> cur, List<List<Integer>> res) {
    if (remain == 0) { res.add(new ArrayList<>(cur)); return; }
    for (int i = start; i < a.length && a[i] <= remain; i++) {   // sorted → prune
        cur.add(a[i]);
        combo(a, i, remain - a[i], cur, res);
        cur.remove(cur.size() - 1);
    }
}

// Permutations: track which elements are used.
void permute(int[] a, boolean[] used, List<Integer> cur, List<List<Integer>> res) {
    if (cur.size() == a.length) { res.add(new ArrayList<>(cur)); return; }
    for (int i = 0; i < a.length; i++) {
        if (used[i]) continue;
        used[i] = true; cur.add(a[i]);
        permute(a, used, cur, res);
        used[i] = false; cur.remove(cur.size() - 1);
    }
}

The knobs that differentiate problems

ProblemLoop starts atRecurse withRecord when
Subsetsstarti + 1every node
Combinations (choose k)starti + 1size == k
Combination sum (reuse)startiremain == 0
Permutations0 (skip used)—size == n
Palindrome partitioningstart (end index)end + 1start == n

Constraint problems: N-Queens

Place one queen per row. Track used columns and both diagonals in sets: r − c identifies a "\" diagonal and r + c a "/" diagonal. Each check is O(1), so the whole search prunes heavily.

int totalNQueens(int n) { return place(0, n, new boolean[n], new boolean[2 * n], new boolean[2 * n]); }

int place(int r, int n, boolean[] col, boolean[] d1, boolean[] d2) {
    if (r == n) return 1;
    int count = 0;
    for (int c = 0; c < n; c++) {
        if (col[c] || d1[r - c + n] || d2[r + c]) continue;
        col[c] = d1[r - c + n] = d2[r + c] = true;
        count += place(r + 1, n, col, d1, d2);
        col[c] = d1[r - c + n] = d2[r + c] = false;
    }
    return count;
}

Complexity cheat sheet

GeneratesCountTime
Subsets2ⁿO(n · 2ⁿ)
Permutationsn!O(n · n!)
Combinations C(n, k)n! / (k!(n−k)!)O(k · C(n, k))
Practice problems
  • Subsetsmedium
  • Subsets IIsort, skip duplicatesmedium
  • Permutationsmedium
  • Permutations IImedium
  • Combinationsmedium
  • Combination Summedium
  • Combination Sum IImedium
  • Letter Combinations of a Phone Numbermedium
  • Generate Parenthesesopen < n, close < openmedium
  • Palindrome Partitioningmedium
  • Word Searchmedium
  • N-Queenshard
  • Sudoku Solverhard
Key takeaways
  • Choose → explore → un-choose.
  • start index for subsets/combinations; a used[] array for permutations.
  • Sort and skip equal neighbours at the same depth to remove duplicates.
  • Prune early: sorted input with break, sets for O(1) constraint checks.
  • Always record a copy of the path.