mediumBacktrackingRecursion target 25 min
All subsets
You get a list nums of different integers. Return every subset of it, as a list of lists. A subset keeps some of the numbers and drops the rest: it can keep none of them (the empty list []) or all of them.
Each subset must appear exactly once. Return the subsets in any order, and the numbers inside each subset in any order: [5, 2] and [2, 5] are the same subset, so only one of them may appear.
Example 1
Input
nums = [2, 5, 9]Output[[2, 5, 9], [2, 5], [2, 9], [2], [5, 9], [5], [9], []]Each of the 3 numbers is kept or dropped: 2 × 2 × 2 = 8 subsets, from all three down to none.
Example 2
Input
nums = [6]Output[[6], []]Keep the 6 or drop it.
Example 3
Input
nums = []Output[[]]An empty list still has one subset: the empty one.
Constraints
0 ≤ len(nums) ≤ 10
-10 ≤ nums[i] ≤ 10
All numbers in
numsare different.
Plan it first
Write a line for each before you code, then say them out loud. Compare with the Approach tab afterwards.
Run examples checks the examples. Submit runs every test, including edge cases and, when the problem has one, a speed check on a large input.