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.
MediumOpen on LeetCode ↗
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
02
13
2path = []
result (0)
empty
Start with an empty path and call backtrack(0).
1function subsets(nums: number[]): number[][] {2const result: number[][] = [];3const path: number[] = [];4function backtrack(start: number) {5result.push([...path]);6for (let i = start; i < nums.length; i++) {7path.push(nums[i]);8backtrack(i + 1);9path.pop();10}11}12backtrack(0);13return result;14}