Subsets Problem
Description
LeetCode Problem 78.
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.
Example 1:
Input: nums = [1,2,3]
Output: [[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
Example 2:
Input: nums = [0]
Output: [[],[0]]
Constraints:
- 1 <= nums.length <= 10
- -10 <= nums[i] <= 10
- All the numbers of nums are unique.
Solution
Approach: Build Subsets Number by Number (Cascading)
Every subset either leaves a number out or takes it. So if we already have all subsets of the first few numbers, we get all subsets with one more number by keeping each existing subset (leave it out) and adding a copy of it with the new number (take it).
- Start with one subset, the empty one:
[[]]. - For each
numberinnums, go over the subsets that exist right now and append a copy of each withnumberadded.
For nums = [1, 2, 3]:
start: []
after 1: [], [1]
after 2: [], [1], [2], [1,2]
after 3: [], [1], [2], [1,2], [3], [1,3], [2,3], [1,2,3]
Each step doubles the list, so we end with 2n subsets, and since the numbers are unique, no subset appears twice.
The detail to get right is the loop bound: remember how many subsets there are before the step starts and only extend those. Looping until the end of the growing list would also extend the subsets added in this same step and never stop. Also, each new subset must be a copy, not the old list with the number pushed onto it.
Complexity: O(n · 2n) time and O(n · 2n) space for the output, where n is the length of nums.
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
subsets = [[]] # the subsets of the numbers seen so far
for number in nums:
# Each existing subset either leaves number out (kept as is) or takes it (a new copy).
for i in range(len(subsets)):
subsets.append(subsets[i] + [number])
return subsets
Now write it from memory
Close the write-up and solve it yourself against the tests.