This is LeetCode #78: Subsets — the fundamental backtracking problem! 🎒
💡 Think of it like this: You're packing a bag and you have 3 items. For each item, you have 2 choices: put it in or leave it out. That means 2×2×2 = 8 possible combinations!
The Decision Tree: For each number, we make a choice — include it or not:
The Backtracking Template:
💭 Your turn! Take what you learned above and write the code yourself. Struggling is part of learning! 🧠
Key backtracking concepts:
Complexity: Time O(n × 2ⁿ) — 2ⁿ subsets, each up to length n. Space O(n) for recursion depth.
def subsets(nums):
result = []
def backtrack(start, current):
result.append(current[:]) # Add a COPY of current subset
for i in range(start, len(nums)):
current.append(nums[i]) # Choose
backtrack(i + 1, current) # Explore
current.pop() # Un-choose (backtrack!)
backtrack(0, [])
return result
Run your code
[]
[1]
[1, 2]
...