Subsets
Master this topic with zero to advance depth.
Subsets
The Power Set
A power set of is the set of all subsets of , including the empty set and itself. For a set with elements, there are subsets.
Inclusion-Exclusion Principle
At each step, we have two choices for the current element: either include it in the current subset or exclude it.
Generate all possible subsets (the power set) of a set of unique integers. Includes visual inclusion-exclusion trace.
Examples
Level I: Recursive Backtracking (Include/Exclude)
Intuition
At each step, we decide whether to add nums[i] to our subset or not.
Use a recursive function dfs(idx, current). In one branch, add nums[idx] and recurse. In the other, don't add it and recurse.
Detailed Dry Run
Dry Run: nums=[1,2]
| idx | path | Decision | Next State |
| :-- | :---: | :--- | :--- |
| 0 | [] | Include 1| DFS(1, [1])|
| 1 | [1] | Include 2| DFS(2, [1,2]) -> RES: [1,2]|
| 1 | [1] | Exclude 2| DFS(2, [1]) -> RES: [1]|
| 0 | [] | Exclude 1| DFS(1, []) |
| 1 | [] | Include 2| DFS(2, [2]) -> RES: [2]|
| 1 | [] | Exclude 2| DFS(2, []) -> RES: []|Level II: Cascading (Iterative Generation)
Intuition
Start with an empty set and gradually build the power set.
Start with [[]]. For each number in nums, duplicate all existing subsets and add the current number to the duplicates.
Detailed Dry Run
nums=[1,2]
- res = [[]]
- num=1: res = [[], [1]]
- num=2: res = [[], [1], [2], [1,2]]
Level III: Bit Manipulation (Bitmask)
Intuition
Each subset of a set with elements can be uniquely mapped to a binary number from to .
Loop from i = 0 to 2^N - 1. For each i, if the -th bit is 1, include nums[j] in the current subset.
Detailed Dry Run
nums=[1,2]
- i=0 (00): []
- i=1 (01): [1]
- i=2 (10): [2]
- i=3 (11): [1,2]
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.