Backtracking and subsets
Enumerating combinations: subsets, combinations, N-Queens, Sudoku. Prune as soon as a partial answer is invalid.
High interview relevanceRoadmap: Advanced
| Time | O(2ⁿ) subsets; O(n · 2ⁿ) including copying each one |
|---|---|
| Space | O(n) recursion, plus stored output |
Why it costs this much
Each item is either included or excluded, so there are 2ⁿ leaves in the recursion tree.
Code
def subsets(nums):
res, cur = [], []
def go(i):
if i == len(nums):
res.append(cur[:]) # 2^n leaves; each copy costs O(n)
return
go(i + 1) # exclude nums[i]
cur.append(nums[i])
go(i + 1) # include nums[i]
cur.pop()
go(0)
return resCommon pitfalls
Copying each result adds a factor of n to the time. Pruning helps in practice but often does not change the worst-case bound.