Skip to content
Problem 78 · LeetCode 78(opens in a new tab)

Subsets

MediumBacktracking

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.

Try it on LeetCode(opens in a new tab)
  1. Bitmask for each subsetO(n · 2^n)
  2. Grow the list one number at a timeO(n · 2^n)
  3. BacktrackingO(n · 2^n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 10 numbers (1,024 subsets)Verdict
Bitmask for each subsetO(n · 2^n)
Passes; short, no recursion
Grow the list one number at a timeO(n · 2^n)
Passes; easy to explain
BacktrackingO(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 path itself instead of a copy, so every saved subset ends up as the same list, emptied by the pops.
  • Looping from 0 instead of start in 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

  1. 1Clarify. Are the numbers distinct? Does the empty subset count? Does the order of subsets matter?
  2. 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.
  3. 3Pick a shape. Mention the bitmask version, then say you will backtrack because the pattern extends to the follow-ups.
  4. 4Code push, recurse, pop. Record a copy of the path on entry, and start the loop at start so each subset appears once.
  5. 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?