Subsets

Medium

Topics
ArrayBacktrackingBit Manipulation

Given an array nums of unique integers, return all possible subsets (the power set). The result may be in any order; this judge compares them order-independently.

Example 1

[][1][2][1,2][3][1,3][2,3][1,2,3]
Each chip is one subset. Every element is independently in or out, which is why the empty set and the whole array both count, and why there are exactly 8 of them. The input holds no duplicates, so no two subsets come out equal.
Each chip is one subset.
Input:  nums = [1,2,3]
Output: [[],[1],[2],[3],[1,2],[1,3],[2,3],[1,2,3]]

Example 2

[][0]
Input:  nums = [0]
Output: [[],[0]]

Constraints

  • 1 <= nums.length <= 10
  • All numbers are unique.
Editorial — intuition, approach, complexity and pitfalls

Intuition

Each element is either in a subset or not — that binary choice over n elements generates all 2^n subsets. Backtracking explores the include/exclude tree.

Approach

  1. DFS carrying the current index and partial subset.
  2. At each index, record the current subset, then try adding each later element.
  3. Alternatively enumerate bitmasks 0..2^n-1.

Dry Run

nums = [1, 2, 3]
Every node of the recursion tree IS a subset -- there is no "is it complete?"
test, because the path is emitted on arrival:
  emit []           loop i from 0
    emit [1]          loop i from 1
      emit [1, 2]       loop i from 2
        emit [1, 2, 3]  loop i from 3, nothing left
      emit [1, 3]       loop i from 3
    emit [2]          loop i from 2
      emit [2, 3]       loop i from 3
    emit [3]          loop i from 3
answer [] | [1] | [1,2] | [1,2,3] | [1,3] | [2] | [2,3] | [3]
`start` is what prevents duplicates without any sorting or set. Element i may
only be followed by elements after it, so each subset is generated in exactly one
order -- [1,3] is reachable but [3,1] is not. Recurse from i instead of i + 1 and
an element can follow itself, so the search never terminates: RecursionError.
Moving the emit below the loop does NOT empty the output, which is worth knowing
if you are told it does. `path.pop()` runs after each recursive call returns, so
path still holds the current subset when the function ends. All eight subsets
still appear, in post-order instead of pre-order:
[1,2,3] [1,2] [1,3] [1] [2,3] [2] [3] []. The set is identical and only the
ORDER changes -- which is still a failure against a judge that fixes the order,
just not for the reason you might expect.

Complexity

  • Time — O(n * 2^n): there are 2^n subsets, each copied in O(n).
  • Space — O(n): recursion depth (excluding output).

Common Pitfalls

  • Record the path before the loop, not after — but not because moving it below empties the output, which it does not. path.pop() runs after each recursive call returns, so path still holds the current subset when the function ends, and all eight subsets are still emitted, in post-order: [1,2,3] [1,2] [1,3] [1] [2,3] [2] [3] []. The set is identical and only the order changes, which still fails a judge that fixes the order.
  • Recurse from i + 1. Passing i allows an element to be reused, so the search never terminates and dies with RecursionError.

Full Solution — all languages

class Solution:
    def subsets(self, nums):
        res=[]
        def dfs(start,path):
            res.append(path[:])
            for i in range(start,len(nums)):
                path.append(nums[i]); dfs(i+1,path); path.pop()
        dfs(0,[])
        return res
SensAI
Beta
Tap the mic to stop voice mode