You are given a list nums of distinct whole numbers. A subset is any selection of them: none, some or all.
Return every possible subset, each one exactly once. The subsets may come back in any order, and so may the numbers inside each subset.
Example 1
Input: nums = [4, 7, 2] Output: [[], [4], [7], [4, 7], [2], [4, 2], [7, 2], [4, 7, 2]] Why: each number is either in or out: 2 × 2 × 2 = 8 subsets
2 more examples and the constraints
Example 2
Input: nums = [5] Output: [[], [5]] Why: take the 5, or take nothing
Example 3
Input: nums = [-3, 0] Output: [[], [-3], [0], [-3, 0]] Why: the empty subset always counts
Constraints
- 1 ≤ length of nums ≤ 10
- Every number is between −10 and 10
- No number appears twice
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Bitmask for each subsetO(n · 2^n)
- Grow the list one number at a timeO(n · 2^n)
- BacktrackingO(n · 2^n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10 numbers (1,024 subsets) | Verdict |
|---|---|---|---|
| Bitmask for each subset | O(n · 2^n) | Passes; short, no recursion | |
| Grow the list one number at a time | O(n · 2^n) | Passes; easy to explain | |
| Backtracking | O(n · 2^n) | Best; the pattern for every follow-up |
n = how many numbers. Every approach must write 2^n subsets, so none can beat O(n · 2^n).
Edge cases to test
- The empty subset.
[]is always part of the answer, even though it holds nothing. - One number. [5] gives exactly two subsets:
[]and[5]. - Negatives and zero. 0 is a real number to choose, not a placeholder. [-3, 0] has four subsets.
- Ten numbers. The largest input has 1,024 subsets. Fine to list, but do not try anything slower than one step per subset.
Common mistakes
- Recording
pathitself instead of a copy, so every saved subset ends up as the same list, emptied by the pops. - Looping from 0 instead of
startin each call, which creates [7, 4] as well as [4, 7]. - Forgetting to pop after the recursive call, so numbers from one branch leak into the next.
How to talk through it
- 1Clarify. Are the numbers distinct? Does the empty subset count? Does the order of subsets matter?
- 2Count the answer. Each number is in or out, so there are 2^n subsets. Say no approach can beat O(n · 2^n), because that is the size of the output.
- 3Pick a shape. Mention the bitmask version, then say you will backtrack because the pattern extends to the follow-ups.
- 4Code push, recurse, pop. Record a copy of the path on entry, and start the loop at
startso each subset appears once. - 5Test out loud. Run [5] and [4, 7, 2]; check you get 2 and 8 subsets and that [] is there.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?