|
| 1 | +# 78. Subsets |
| 2 | + |
| 3 | +## Recursive Solution |
| 4 | +- Runtime: O(2^N) |
| 5 | +- Space: O(N) |
| 6 | +- N = Number of elements in array |
| 7 | + |
| 8 | +Using the ability for recursion to backtrack will allow us to populate the result. |
| 9 | +During each recursion, we will loop through the given array, during this loop, the number represent a choosen number for the subset. |
| 10 | +The numbers that were not choosen yet will be passed to the next recursion to be choosen again, hence, creating the result. |
| 11 | +By keeping a stack, we can use it as we traverse/recur, we append prior and pop after using this stack to add to the result of subsets. |
| 12 | + |
| 13 | +You can visually map this out using this example: |
| 14 | + |
| 15 | +Input: [1,2,3] |
| 16 | + |
| 17 | +1. R1: Select 1 -> [1] |
| 18 | +2. R2: Select 2 -> [1,2] |
| 19 | +3. R3: Select 3 -> [1,2,3] -> Pop 3 -> Done |
| 20 | +5. R2: Pop 2 -> Select 3 -> [1,3] -> Pop 3 -> Done |
| 21 | +7. R1: Pop 1 -> Select 2 -> [2] |
| 22 | +8. R2: Select 3 -> [2,3] -> Pop 3 -> Done |
| 23 | +9. R1: Select 3 -> [3] -> Pop 3 -> Done |
| 24 | + |
| 25 | +``` |
| 26 | +class Solution: |
| 27 | + def subsets(self, nums: List[int]) -> List[List[int]]: |
| 28 | + results = list() |
| 29 | + results.append([]) |
| 30 | + self.subset_helper(nums, [], results) |
| 31 | + return results |
| 32 | + |
| 33 | + def subset_helper(self, nums, curr_result, results): |
| 34 | + for index, n in enumerate(nums): |
| 35 | + curr_result.append(n) |
| 36 | + results.append([str(n) for n in curr_result]) |
| 37 | + self.subset_helper(nums[index+1:], curr_result, results) |
| 38 | + curr_result.pop() |
| 39 | +``` |
0 commit comments