LeetCode #78 Medium

Subsets (Power Set)

Subsets (Power Set) is LeetCode 78 (Medium). Given an array nums of distinct integers, return every subset of it, from the empty list to the whole array. This collection is called the power set, and it may be returned in any order.

  • n elements give 2^n subsets. With n at most 10, the answer has at most 1,024 lists.
  • All elements are different, so no two subsets can come out equal.
Constraints
  • 1 <= nums.length <= 10
  • -10 <= nums[i] <= 10
  • All the numbers of nums are unique.
backtrackingbit-manipulation
Open on LeetCode ↗
02

Intuition

Walk the array from left to right and make one yes/no decision per element: put it in the current subset, or leave it out. A full set of decisions describes exactly one subset, and two different sets of decisions always give different subsets.

Draw the decisions as a binary tree. Level i decides nums[i]: the left branch takes it and the right branch skips it. After n levels every element is decided, so each of the 2^n leaves is one finished subset.

Backtracking walks this tree with one shared list, path. It appends before the take branch, removes the element before the skip branch, and saves a copy at every leaf.

How to spot this pattern

This is the standard power set backtracking pattern: every element is independently in or out, and you must list every outcome. Combinations, Subsets II and many "choose some items" problems are this tree with extra rules.

03

Approach

Try it first

Before reading on, draw the tree of choices for [1, 2] by hand: which branch adds 2, and what must path look like when you come back up? Aim for O(n · 2^n) time.

1

Keep one list for the current subset

path holds the elements chosen so far and res collects finished subsets. Sharing one list means no new list is built at each call, only one copy per finished subset.

2

Take the element and go deeper

At index i, append nums[i] to path and call dfs(i + 1). Every subset found below this call contains nums[i], because it stays in path until that call returns.

3

Undo, then skip it

Pop nums[i] and call dfs(i + 1) again. The path is back to what it was before the take, so this second branch finds every subset without nums[i].

4

Save a copy at the end of the array

When i == len(nums), every element has been decided, so the path is one complete subset. Append a copy of it to res and return to the caller.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def subsets(self, nums):
▶3 res, path = [], []
▶4 
▶5 def dfs(i):
▶6 if i == len(nums):
▶7 res.append(path[:])
▶8 return
▶9 path.append(nums[i])
▶10 dfs(i + 1)
▶11 path.pop()
▶12 dfs(i + 1)
▶13 
▶14 dfs(0)
▶15 return res
takeskip∅1path1saved 0 of 8take 1 → path 1
i0deciding 1
path[1]
Left branch: put 1 in the subset and decide the next element. Every subset found below this node contains 1.
takeskip∅11 2path12saved 0 of 8take 2 → path 1 2
i1deciding 2
path[1, 2]
Left branch: put 2 in the subset and decide the next element. Every subset found below this node contains 2.
takeskip∅11 21 2 3path123saved 0 of 8take 3 → path 1 2 3
i2deciding 3
path[1, 2, 3]
Left branch: put 3 in the subset and decide the next element. Every subset found below this node contains 3.
takeskip∅11 21 2 3path123saved 1 of 8every number decided → save 1 2 3
i3end of nums
saved1
Every element has been taken or skipped on the way down, so the path [1, 2, 3] is one complete subset. A copy goes into the result, because the same list keeps changing as the search goes on.
takeskip∅11 21 2 31 2path12saved 1 of 8remove 3, skip it → path 1 2
i2deciding 3
path[1, 2]
Every subset with 3 on this branch is saved. Pop 3 so the path is back to [1, 2], then take the right branch: the same choices without 3.
takeskip∅11 21 2 31 2path12saved 2 of 8every number decided → save 1 2
i3end of nums
saved2
Every element has been taken or skipped on the way down, so the path [1, 2] is one complete subset. A copy goes into the result, because the same list keeps changing as the search goes on.
takeskip∅11 211 2 31 2path1saved 2 of 8remove 2, skip it → path 1
i1deciding 2
path[1]
Every subset with 2 on this branch is saved. Pop 2 so the path is back to [1], then take the right branch: the same choices without 2.
takeskip∅11 211 2 31 21 3path13saved 2 of 8take 3 → path 1 3
i2deciding 3
path[1, 3]
Left branch: put 3 in the subset and decide the next element. Every subset found below this node contains 3.
takeskip∅11 211 2 31 21 3path13saved 3 of 8every number decided → save 1 3
i3end of nums
saved3
Every element has been taken or skipped on the way down, so the path [1, 3] is one complete subset. A copy goes into the result, because the same list keeps changing as the search goes on.
takeskip∅11 211 2 31 21 31path1saved 3 of 8remove 3, skip it → path 1
i2deciding 3
path[1]
Every subset with 3 on this branch is saved. Pop 3 so the path is back to [1], then take the right branch: the same choices without 3.
takeskip∅11 211 2 31 21 31path1saved 4 of 8every number decided → save 1
i3end of nums
saved4
Every element has been taken or skipped on the way down, so the path [1] is one complete subset. A copy goes into the result, because the same list keeps changing as the search goes on.
takeskip∅1∅1 211 2 31 21 31pathemptysaved 4 of 8remove 1, skip it → path empty
i0deciding 1
path[]
Every subset with 1 on this branch is saved. Pop 1 so the path is back to [], then take the right branch: the same choices without 1.
takeskip∅1∅1 2121 2 31 21 31path2saved 4 of 8take 2 → path 2
i1deciding 2
path[2]
Left branch: put 2 in the subset and decide the next element. Every subset found below this node contains 2.
takeskip∅1∅1 2121 2 31 21 312 3path23saved 4 of 8take 3 → path 2 3
i2deciding 3
path[2, 3]
Left branch: put 3 in the subset and decide the next element. Every subset found below this node contains 3.
takeskip∅1∅1 2121 2 31 21 312 3path23saved 5 of 8every number decided → save 2 3
i3end of nums
saved5
Every element has been taken or skipped on the way down, so the path [2, 3] is one complete subset. A copy goes into the result, because the same list keeps changing as the search goes on.
takeskip∅1∅1 2121 2 31 21 312 32path2saved 5 of 8remove 3, skip it → path 2
i2deciding 3
path[2]
Every subset with 3 on this branch is saved. Pop 3 so the path is back to [2], then take the right branch: the same choices without 3.
takeskip∅1∅1 2121 2 31 21 312 32path2saved 6 of 8every number decided → save 2
i3end of nums
saved6
Every element has been taken or skipped on the way down, so the path [2] is one complete subset. A copy goes into the result, because the same list keeps changing as the search goes on.
takeskip∅1∅1 212∅1 2 31 21 312 32pathemptysaved 6 of 8remove 2, skip it → path empty
i1deciding 2
path[]
Every subset with 2 on this branch is saved. Pop 2 so the path is back to [], then take the right branch: the same choices without 2.
takeskip∅1∅1 212∅1 2 31 21 312 323path3saved 6 of 8take 3 → path 3
i2deciding 3
path[3]
Left branch: put 3 in the subset and decide the next element. Every subset found below this node contains 3.
takeskip∅1∅1 212∅1 2 31 21 312 323path3saved 7 of 8every number decided → save 3
i3end of nums
saved7
Every element has been taken or skipped on the way down, so the path [3] is one complete subset. A copy goes into the result, because the same list keeps changing as the search goes on.
takeskip∅1∅1 212∅1 2 31 21 312 323∅pathemptysaved 7 of 8remove 3, skip it → path empty
i2deciding 3
path[]
Every subset with 3 on this branch is saved. Pop 3 so the path is back to [], then take the right branch: the same choices without 3.
takeskip∅1∅1 212∅1 2 31 21 312 323∅pathemptysaved 8 of 8every number skipped → save the empty subset
i3end of nums
saved8
Every element has been taken or skipped on the way down, so the path [] is one complete subset. A copy goes into the result, because the same list keeps changing as the search goes on.
takeskip∅1∅1 212∅1 2 31 21 312 323∅pathemptysaved 8 of 8all 8 subsets saved → return them
len(res)82^3
result[[1, 2, 3], [1, 2], [1, 3], [1], [2, 3], [2], [3], []]
Each of the 8 leaves is one set of take-or-skip choices, and no two leaves made the same choices, so the result has every subset exactly once. The path is empty again because every take was undone.
05

Bitmask counting

Another way to generate all subsets is to count. Every number from 0 to 2^n − 1 has n bits, and bit j says whether nums[j] is in. Mask 5 is binary 101, so with [1, 2, 3] it picks 1 and 3. The 2^n masks are exactly the 2^n subsets.

▶1class Solution:
▶2 def subsets(self, nums):
▶3 n = len(nums)
▶4 res = []
▶5 for mask in range(1 << n):
▶6 res.append([nums[j] for j in range(n) if mask >> j & 1])
▶7 return res
06

Common pitfalls

Saving the shared list instead of a copy

✗ Wrong
res.append(path)
✓ Right
res.append(path[:])

Every entry of res then points at the same list, which is empty once the search finishes. For [1, 2, 3] the result is eight empty lists. In Java, add new ArrayList<>(path); C++ push_back(path) already copies.

Skipping without undoing the take

✗ Wrong
path.append(nums[i])
dfs(i + 1)
dfs(i + 1)
✓ Right
path.append(nums[i])
dfs(i + 1)
path.pop()
dfs(i + 1)

The skip branch then still carries nums[i]. For [1] the result is [[1], [1]] instead of [[1], []], and longer inputs collect ever-growing lists.

07

Complexity

Time
O(n · 2^n)
Space
O(n)
The tree has 2^n leaves and copying one subset costs up to n. The 2^(n+1) − 1 calls each do O(1) other work. Apart from the output, only the recursion stack and path are stored, each at most n deep.
08

Subsets (Power Set) FAQ

Why is my output in a different order from the expected one?

Any order is accepted. Taking before skipping puts [1, 2, 3] first and [] last; skipping first reverses that. The judge compares the collections, not the positions.

Can I just use itertools.combinations?

Yes: chaining combinations(nums, r) for every r from 0 to n gives the power set in the same O(n · 2^n). Interviewers usually want the recursion, though, because Subsets II and Combination Sum build on it.

What changes when the array has duplicates?

Taking either of two equal values gives the same subset, so the tree produces repeats. Subsets II sorts the array and skips a value that equals the one tried just before it at the same level.