Algorithm patterns← All patterns

Pattern 07 / 10 · Advanced

Backtracking

Try a choice, explore everything after it, then undo it and try the next.

The idea

Keep one growing path. At each step, choose an option, recurse to explore everything that starts with that choice, then pop it off and try the next option. The path is shared, so undoing the last move is all it takes to go back.

time O(n · 2ⁿ) for subsetsspace O(n) for the path, plus the output

Reach for it when

  • You must list every subset, permutation or combination.
  • You build an answer step by step and some partial answers can be abandoned early.
  • Constraints are small (n ≈ 10–20) because the output itself is exponential.

Watch it run

78. Subsets

Return every possible subset of an array of unique numbers.

Example 1

Input: nums = [1, 2, 3]

Output: [[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]]

Example 2

Input: nums = [0]

Output: [[], [0]]

WALKTHROUGH INPUT · nums = [1, 2, 3]

start
1
0
2
1
3
2
path = []

result (0)

empty

Start with an empty path and call backtrack(0).

1 / 24
solution.ts
1function subsets(nums: number[]): number[][] {
2 const result: number[][] = [];
3 const path: number[] = [];
4 function backtrack(start: number) {
5 result.push([...path]);
6 for (let i = start; i < nums.length; i++) {
7 path.push(nums[i]);
8 backtrack(i + 1);
9 path.pop();
10 }
11 }
12 backtrack(0);
13 return result;
14}

Practice next