The problem, in one line. Given distinct numbers, return every group you can form from them, including the empty group. LeetCode 78.
The tell. “All possible” groups from a short list. Each item is either in or out, so the answer is a tree of yes-or-no choices, and you walk the whole tree.
The wrong first idea
Write one loop per number. For three numbers that is three nested loops.
for a in (None, nums[0]):
for b in (None, nums[1]):
for c in (None, nums[2]):
...
It works for exactly three numbers. The input can have ten, and you do not know which until the program runs, so you cannot write the right number of loops.
The invariant
The clinic Clinic #13: Subsets walks this tree in full. In short: keep one list called path. Record it at every node, then for each remaining number add it, go deeper, and take it off again.
flowchart TB R["path empty, record"] -->|"add 1"| A["path 1, record"] R -->|"skip to 2"| B["path 2, record"] A -->|"add 2"| C["path 1 2, record"] A -->|"skip to 3"| D["path 1 3, record"]
The sentence that stays true every step: path holds exactly the numbers chosen on the way from the root to here, so every node is one valid subset. Taking the number off after you return is what keeps that true for the next branch.
The solution
def subsets(nums):
res, path = [], []
def dfs(start):
res.append(path[:]) # every node is a subset
for i in range(start, len(nums)):
path.append(nums[i]) # choose
dfs(i + 1)
path.pop() # un-choose
dfs(0)
return res
print(subsets([1, 2, 3]))
print(subsets([0]))
print(subsets([]))
[[], [1], [1, 2], [1, 2, 3], [1, 3], [2], [2, 3], [3]]
[[], [0]]
[[]]
func subsets(nums []int) [][]int {
res, path := [][]int{}, []int{}
var dfs func(start int)
dfs = func(start int) {
res = append(res, append([]int{}, path...)) // every node is a subset
for i := start; i < len(nums); i++ {
path = append(path, nums[i]) // choose
dfs(i + 1)
path = path[:len(path)-1] // un-choose
}
}
dfs(0)
return res
}
Same three calls print [[] [1] [1 2] [1 2 3] [1 3] [2] [2 3] [3]], [[] [0]] and [[]].
Complexity
- Time O(n times 2^n): there are 2 to the n subsets and copying each one costs up to n.
- Space O(n) besides the answer: the recursion is at most n deep and
pathholds at most n numbers.
Traps
- Recording
pathwithout copying. The same list is shared and emptied by the pops, so[1, 2, 3]returns eight empty lists. - Recursing with
start + 1instead ofi + 1.[1, 2, 3]then returns 16 lists with repeats like[2, 2]and[3, 3, 3]. - Forgetting the empty subset. The answer for one number must have two entries, so
[0]returns[[], [0]].
Next in the ladder
Combination Sum keeps the same tree but cuts a branch the moment its running total passes the target, and lets a number be used again.