Python coding

Every subset

Given a list nums of distinct integers, return every subset of it, including the empty one and nums itself. Each subset must appear exactly once; the order of the subsets, and of the numbers inside each subset, does not matter.

0 ≤ len(nums) ≤ 10, so the answer has at most 2¹⁰ = 1,024 subsets.

  • all_subsets([1,2,3]) → [[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]
  • all_subsets([0]) → [[],[0]]
  • all_subsets([]) → [[]]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Picture a decision tree: each node is a partial subset, and every node, not only the leaves, is already a valid answer.

Hint 2

Record path[:] on entry, then for each i from start: append nums[i], recurse with i + 1, pop. Starting at i + 1 avoids building both {1, 2} and {2, 1}.

Solution and why it works
pythonO(n·2ⁿ) · O(n) recursion depth, beyond the output
def all_subsets(nums: list[int]) -> list[list[int]]:
    res, path = [], []

    def bt(start: int) -> None:
        res.append(path[:])
        for i in range(start, len(nums)):
            path.append(nums[i])
            bt(i + 1)
            path.pop()

    bt(0)
    return res

Every node of the decision tree is a subset, so the function records a copy of path on entry, not only at the leaves. The start index lets a number be picked only after the ones before it, so each subset is built in a single order and never repeats. The classic trap is res.append(path): every entry aliases one list, which is empty when the search ends.