Subsets (Power Set)
Generate all possible subsets of a set of unique integers.
Problem Understanding
Given an integer array nums of unique elements, return all possible subsets (the power set).
Example: nums = [1, 2, 3]
- Output:
[], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3]
There should be $2^N$ subsets.
Algorithm Strategy
We can use the Choose/Not Choose pattern.
For each element in the array, we have exactly two choices:
- Include it in the current subset.
- Exclude it from the current subset.
We iterate from index 0 to n. At each index, we branch into these two possibilities.
Interactive Visualization
Initializing...
Watch how the tree expands. Each level represents an index in nums.
Try clicking 'Randomize' to see how the tree changes with different input arrays.
Dry Run
nums = [1, 2]
| Index | Current Subset | Decision | Resulting State |
|---|---|---|---|
| 0 | [] |
Include 1 | dfs(i=1, sub=[1]) |
| 1 | [1] |
Include 2 | dfs(i=2, sub=[1, 2]) |
| 2 | [1, 2] |
Base Case | Add [1, 2] |
| 1 | [1] |
Backtrack | Pop 2 -> [1] |
| 1 | [1] |
Exclude 2 | dfs(i=2, sub=[1]) |
| 2 | [1] |
Base Case | Add [1] |
| 0 | [] |
Backtrack | Pop 1 -> [] |
| 0 | [] |
Exclude 1 | dfs(i=1, sub=[]) |
| 1 | [] |
Include 2 | dfs(i=2, sub=[2]) |
| 2 | [2] |
Base Case | Add [2] |
Edge Cases & Common Mistakes
Watch out for these pitfalls:
Empty Input:
nums = []should return[[]], not[].Duplicate Elements: This specific problem assumes unique elements. If duplicates were allowed (Subsets II), you would need to sort and skip duplicates to avoid generating the same subset twice.
Reference Trap: A very common bug in Java/Python is adding the
currentlist reference toresult. Sincecurrentkeeps changing, your final result will be a list of empty lists. Always usenew ArrayList<>(current)orsubset.copy().
Solution
Standard Backtracking implementations.
1class Solution:2 def subsets(self, nums: List[int]) -> List[List[int]]:3 res = []4 subset = []56 def dfs(i):7 if i >= len(nums):8 res.append(subset.copy())9 return1011 # Decision 1: Include nums[i]12 subset.append(nums[i])13 dfs(i + 1)1415 # Decision 2: Exclude nums[i]16 subset.pop()17 dfs(i + 1)1819 dfs(0)20 return res
Complexity Analysis
- Time Complexity: O(N * 2^N). There are $2^N$ subsets, and each can take O(N) to copy/generate.
- Space Complexity: O(N) for recursion stack.
- Problem Understanding
- Algorithm Strategy
- Interactive Visualization
- Dry Run
- Edge Cases & Common Mistakes
- Solution
- Complexity Analysis
