List every subset of a collection of distinct values, including choosing no values at all.
Problem
Input. A list nums of distinct integers.
Output. Return one list for each subset, including the empty subset and the subset containing every value.
Rules. A value may be selected at most once per subset; changing selection order does not create a new subset.
Leave the input unchanged. Each returned list must be independent of the others.
Output order is not required. Empty input returns [[]]; duplicate values require the separate policy below.
Example. [1, 2, 3] has eight subsets: [[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]].
The selections [1, 2] and [2, 1] are the same subset, not two answers.
Picture
Each node is a saved path; each edge chooses one input index. Indices increase along every root-to-node route, so an unordered selection has only one construction order.
Increasing indices choose membership without emitting every ordering
Reference drawing
Increasing indices choose membership without emitting every ordering
Derivation
Read it this way: save a copy at every node. Return along an edge by undoing its choice before trying a sibling.
At choose(start), the path contains only earlier, strictly increasing positions.
This call may extend it using any index from start onward.
It owns each append that it later removes.
Reference drawing
Problem trace
Increasing choice indices generate each subset once, including the empty subset
Execution trace
- active call
- (0, 0)
- input
- nums = [1, 2, 3]
- columns
- path | start
- active call
- (0, 0)→(1, 0)
- action
- save []→append 1; save [1]
- answer
- [[]]→[[], [1]]
- active call
- (1, 0)→(2, 0)
- action
- append 1; save [1]→append 2; save [1,2]
- answer
- [[], [1]]→3 subsets saved
- active call
- (2, 0)→(3, 0)
- action
- append 2; save [1,2]→save [1,2,3]; return; pop 3
- answer
- 3 subsets saved→4 subsets saved
- active call
- (3, 0)→(2, 0)
- action
- save [1,2,3]; return; pop 3→pop 2; append 3; save [1,3]
- answer
- 4 subsets saved→5 subsets saved
- active call
- (2, 0)→(1, 0)
- action
- pop 2; append 3; save [1,3]→pop 3; pop 1; append 2; save [2]
- answer
- 5 subsets saved→6 subsets saved
- active call
- (1, 0)→(2, 0)
- action
- pop 3; pop 1; append 2; save [2]→append 3; save [2,3]
- answer
- 6 subsets saved→7 subsets saved
- active call
- (2, 0)→(1, 0)
- action
- append 3; save [2,3]→pop 3; pop 2; append 3; save [3]
- result
- not shown→[[],[1],[1,2],[1,2,3],[1,3],[2],[2,3],[3]]
- Recognize it
- Use this pattern when every combination of distinct input positions is valid and order does not matter, so each partial selection must be emitted once.
- Keep true
- On entry to choose(start), path contains indices in strictly increasing order, answer already contains every path visited earlier in DFS order, and only indices start or greater may extend this path.
- Reuse it
- When order should not create duplicates, advance a start boundary after each choice; this same skeleton generates combinations, k-subsets, and increasing-index selections.
Save path.copy(), not path itself.
All recursion levels share the active mutable list, but saved answers must not share that list.
Code
def subsets(nums: list[int]) -> list[list[int]]:
answer: list[list[int]] = []
path: list[int] = []
def choose(start: int) -> None:
answer.append(path.copy())
for index in range(start, len(nums)):
path.append(nums[index])
choose(index + 1)
path.pop()
choose(0)
return answer
There are position subsets.
Materializing their copied lists takes time and output space.
The active path and recursive stack separately use working space.
Python’s recursion limit still applies.
Empty input returns [[]], not [].
Failure Check
Saving path directly makes all answers track the same later mutations.
Forgetting pop leaves a sibling with the previous branch’s state.
Keeping the same start permits reuse instead of selecting each position at most once.
On [1,1], the original emits two separate [1] answers; it has not promised duplicate-value suppression.
Change the Answer Length
New task: Return only selections of a fixed integer length.
Picture and change: Save only complete requested lengths. Stop after saving; prune when too few positions remain. Increasing indices still prevent alternative orderings of one selection.
def k_subsets(nums, size):
answer, path = [], []
def choose(start):
if len(path) == size:
answer.append(path.copy())
return
if len(nums) - start < size - len(path):
return
for index in range(start, len(nums)):
path.append(nums[index])
choose(index + 1)
path.pop()
if size >= 0:
choose(0)
return answer
Check: [1,2,3], size 2, returns [[1,2],[1,3],[2,3]].
Size zero returns [[]]; negative or excessive sizes return [].
Use when: The output-length requirement changes.
Change the Duplicate Policy
New task: Equal input values must not duplicate returned value subsets.
Picture and change: Sort a copy and skip equal choices among siblings only.
A deeper equal position remains available, so [2,2] is still possible.
def unique_subsets(nums):
choices = sorted(nums)
answer, path = [], []
def choose(start):
answer.append(path.copy())
for index in range(start, len(choices)):
if index > start and choices[index] == choices[index - 1]:
continue
path.append(choices[index])
choose(index + 1)
path.pop()
choose(0)
return answer
Check: [1,2,2] returns [[],[1],[1,2],[1,2,2],[2],[2,2]] without changing the input.
Sorting adds work and storage before output enumeration.
Output can still be exponential; fewer duplicates are not a polynomial bound.
Use when: Unique value multisets replace distinct-position selections.
Transfer Check
Why skip duplicate siblings but not every duplicate value?
Answer
Equal sibling choices lead to the same value continuation.
Deeper equal positions represent legitimate multiplicity, such as [2,2].
The skip must depend on the current start boundary.