Skip to the content.

31. Backtracking (Subsets)

Back to the index

Build a solution one choice at a time; after exploring a choice, undo it and try the next. Generates subsets, permutations and combinations, and solves constraint puzzles like N-Queens and Sudoku.

How it works

Backtracking is depth-first search over a tree of decisions. The template is always choose, explore, un-choose: append a choice to path, recurse, then pop it so path is clean for the next option.

For subsets, every node of the decision tree is a valid answer, so we record path on entry. Passing i + 1 as the next start index means each number is only considered after the ones before it, which avoids duplicates like [2, 1].

Diagram

graph TD
    p_root["empty"]
    p_1["1"]
    p_1_2["1 2"]
    p_1_2_3["1 2 3"]
    p_1_2 -->|add 3| p_1_2_3
    p_1 -->|add 2| p_1_2
    p_1_3["1 3"]
    p_1 -->|add 3| p_1_3
    p_root -->|add 1| p_1
    p_2["2"]
    p_2_3["2 3"]
    p_2 -->|add 3| p_2_3
    p_root -->|add 2| p_2
    p_3["3"]
    p_root -->|add 3| p_3

Step-by-step trace

Input: Generate all subsets of [1, 2, 3].

Step Event path Subsets recorded
1 record [] [] 1
2 choose 1 [1] 1
3 record [1] [1] 2
4 choose 2 [1, 2] 2
5 record [1, 2] [1, 2] 3
6 choose 3 [1, 2, 3] 3
7 record [1, 2, 3] [1, 2, 3] 4
8 undo 3 [1, 2] 4
9 undo 2 [1] 4
10 choose 3 [1, 3] 4
11 record [1, 3] [1, 3] 5
12 undo 3 [1] 5
13 undo 1 [] 5
14 choose 2 [2] 5
15 record [2] [2] 6
16 choose 3 [2, 3] 6
17 record [2, 3] [2, 3] 7
18 undo 3 [2] 7
19 undo 2 [] 7
20 choose 3 [3] 7
21 record [3] [3] 8
22 undo 3 [] 8

Result: 8 subsets in this order: [], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3].

Complexity

Operation Time Space
Subsets of n items O(n * 2^n) O(n) recursion plus output
Permutations of n items O(n * n!) O(n) recursion plus output

Python reference implementation

def subsets(nums):
    result, path = [], []

    def backtrack(start):
        result.append(path.copy())          # every node of the tree is a subset
        for i in range(start, len(nums)):
            path.append(nums[i])            # choose
            backtrack(i + 1)                # explore
            path.pop()                      # un-choose

    backtrack(0)
    return result

Common mistakes and tips


The trace above is generated by running the code in dsa/ with python3 tools/build.py, and checked by the tests in tests/.

Previous: Recursion and the Call Stack Next: Dynamic Programming 1D (Coin Change)