PracticeNeetCode ↗LeetCode ↗
Given an integer array nums of unique elements, return all possible subsets (the power set), with no duplicate subsets.
backtrack(start) that first appends a copy of path to the result.i from start to len(nums): append nums[i] to path, recurse with backtrack(i + 1), then pop to undo the choice.backtrack(0) to start the search.Time: O(n · 2ⁿ) — Space: O(n) recursion depth, excluding output
def subsets(nums: list[int]) -> list[list[int]]:
result = []
path = []
def backtrack(start: int) -> None:
result.append(path[:])
for i in range(start, len(nums)):
path.append(nums[i])
backtrack(i + 1)
path.pop()
backtrack(0)
return resultHow the solution above works, piece by piece.
path is the subset being built; result collects copies of it.result.append(path[:]) at the start of every call: every partial choice is itself a valid subset. path[:] copies it, since path keeps changing.for i in range(start, len(nums)): only pick elements after the last one chosen. This fixes an order and prevents duplicates like [1, 2] and [2, 1].append), explore (backtrack(i + 1)), un-choose (pop): the standard backtracking pattern.The recursion tree for nums = [1, 2, 3]: