Subsets
LeetCode 78 · Medium · solution, intuition & step-by-step walkthrough
Record at every node; extend with later indices.
This is how I solved Subsets (LeetCode 78), a medium problem from the Subsets pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a line-by-line debugger.
Intuition
Every subset is a sequence of increasing indices. Starting from each index, either stop (record what you have) or extend with a later element and recurse — that enumerates every subset exactly once.
Approach
- 1
dfs(index, subs) first records a copy of subs.
- 2
For i from index onward: append nums[i], recurse with i+1, pop.
How I solved it
BacktrackingPythonO(n·2ⁿ) time
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
res=[]
def dfs(index,subs):
res.append(subs[:])
for i in range(index,len(nums)):
subs.append(nums[i])
dfs(i+1,subs)
subs.pop()
dfs(0,[])
return resSubsets — FAQ
What is the intuition behind Subsets?
Every subset is a sequence of increasing indices. Starting from each index, either stop (record what you have) or extend with a later element and recurse — that enumerates every subset exactly once.
How do you solve Subsets (LeetCode 78)?
1. dfs(index, subs) first records a copy of subs. 2. For i from index onward: append nums[i], recurse with i+1, pop.
What is the time and space complexity of Subsets?
Time: O(n · 2ⁿ). Space: O(n) recursion. (Accepted approach: Backtracking.)
What are common mistakes in Subsets?
Record a copy (subs[:]) — the list keeps changing.