Subsets by Doubling
nums is a list of distinct integers. Build the list of all of its subsets by this procedure: start with a list that holds only the empty subset []. Then take the elements of nums from left to right; for each element, copy every subset collected so far, append the element to the end of each copy, and add the copies after the subsets already collected, keeping their order. Return the final list of subsets, in exactly that order.
An iterative version of the procedure works, but the recursive one is just as short: the answer for nums is the answer for nums without its last element, followed by those same subsets with the last element appended to each.
For example, [1, 2] gives [[], [1], [2], [1, 2]], and [] gives [[]].
Example 1
Start with [[]]. The element 1 adds [1], giving [[], [1]]. The element 2 adds [2] and [1, 2] after them.
Example 2
There is nothing to add, so only the empty subset remains.
Constraints
0 <= len(nums) <= 7-50 <= nums[i] <= 50- All values in
numsare different
Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.
More Recursion problems
- Sum Then ProductEasy
- Teams of a Given SizeEasy
- The Climb FunctionEasy
- Count the BlobsMedium
- Discs After k MovesMedium
- Distinct Arrangements in OrderMedium
- Every Route Through the GardenMedium
- Fair SplitMedium