Skip to content

Subsets

List every subset of distinct numbers by choosing, exploring and undoing one number at a time.

MediumBacktracking
Solve on LeetCode

The problem

You get an array nums of distinct integers. Return every possible subset of it, including the empty subset and the whole array, with no subset listed twice. The subsets, and the numbers inside each one, can be in any order.

Input nums = [5, 2, 9]

Output [[], [5], [5, 2], [5, 2, 9], [5, 9], [2], [2, 9], [9]]

3 numbers give 2^3 = 8 subsets, from the empty one up to all three numbers.

Input nums = [-4]

Output [[], [-4]]

Even a single number has two subsets: without it and with it.

Key constraint: nums has at most 10 numbers, and n numbers have 2^n subsets, so the output alone is exponential and listing it is the whole job.

How to spot the pattern

  • You must list every combination, not count them or pick the best one.
  • Each number is either in or out, a sequence of small choices that you can make and undo.

The idea

Build subsets one number at a time. Every partial subset you reach is itself an answer, so record it, then try extending it with each number that comes after the last one you added. Only adding later numbers keeps each subset in a single order, so none is produced twice; after exploring a choice, remove the number again and try the next one.

Brute force: Loop over every bitmask from 0 to 2^n - 1 and take the numbers whose bits are set, which is also O(n * 2^n) but doesn't stretch to problems with extra rules the way backtracking does.

Step by step

  1. 1Keep a list current for the subset being built and a list result for the answers.
  2. 2Write backtrack(start), and begin it by adding a copy of current to result.
  3. 3For each index i from start to the end, append nums[i] to current.
  4. 4Call backtrack(i + 1), so deeper picks only use numbers after index i.
  5. 5Remove nums[i] from current again before trying the next i.

See the pattern move

The backtracking pattern on a small example. Step through it, or press play.

Code

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        result = []
        current = []

        def backtrack(start: int) -> None:
            result.append(current.copy())  # every partial subset is an answer
            for i in range(start, len(nums)):
                current.append(nums[i])    # choose nums[i]
                backtrack(i + 1)           # explore with later numbers only
                current.pop()              # undo the choice

        backtrack(0)
        return result

Complexity

Time

O(n * 2^n)

Space

O(n)

There are 2^n subsets and copying each one costs up to n; besides the output, the recursion and current hold at most n numbers.

Watch out for

  • Adding current itself instead of a copy: every saved entry then points to one list, which ends up empty.
  • Looping from 0 instead of from start, which builds [2, 5] after [5, 2] and lists the same subset twice.
  • Recording an answer only when current reaches full length, which loses every smaller subset.

Follow-up questions

What if nums can contain duplicates?

Sort it first, and in the loop skip nums[i] when i > start and it equals nums[i - 1]. That is Subsets II.

Can you do it without recursion?

Start with [[]], and for each number add a copy of every existing subset with that number appended. The bitmask loop works too.

In Hinglish

Har number ke paas do raaste hain: lo ya chhodo. Choose karo, aage explore karo, phir pop karke undo karo, aur har step par current ki copy result mein daalo.

Related problems