MEDIUM NC#71 Backtracking
78. Subsets
📖 Problem
Given an integer array nums of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. Return the solution in any order.
🧠 Visual Learning Aid
1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases
JS/TS Refreshers
- •Array methods (`push`, `pop`, `shift`, `slice`)
- •Object/Map/Set usage patterns
- •Function parameter and return typing
- •Recursive function frames
- •Push/pop state undo
- •Pruning branches early
Logical Thinking Concepts
- •Define invariants before coding
- •Check edge cases first (`[]`, single element, duplicates)
- •Estimate time/space before implementation
- •Apply Backtracking reasoning pattern
- •Apply Recursion reasoning pattern
💡 Approach
- → Use backtracking to generate all subsets
- → At each index, either include or exclude element
- → When reaching end of array, save current subset
- → Time: O(2^n), Space: O(n) for recursion
🧭 Prerequisites
🛠️ Hints & Pitfalls
Hints
- •Use backtracking to generate all subsets
- •At each index, either include or exclude element
- •When reaching end of array, save current subset
Common Pitfalls
- •Time: O(2^n), Space: O(n) for recursion
🧪 Test Cases
Hidden tests on submit: 1
Test Case 1
Not run Input:
subsets([1,2,3]); Expected:
[[], [1], [1,2], [1,2,3], [1,3], [2], [2,3], [3]] Test Case 2
Not run Input:
subsets([0]); Expected:
[[], [0]] Test Case 3
Not run Input:
subsets([]); Expected:
[[]] 📝 Code Editor
📤 Output