|
| 1 | +# time complexity: O(n*2^n) |
| 2 | +# space complexity: O(n) |
| 3 | +from itertools import chain, combinations |
| 4 | +from typing import List |
| 5 | + |
| 6 | + |
| 7 | +class Solution: |
| 8 | + def subsets(self, nums: List[int]) -> List[List[int]]: |
| 9 | + result = [] |
| 10 | + |
| 11 | + def backtrack(start: int, comb: List[int]): |
| 12 | + result.append(list(comb)) |
| 13 | + for i in range(start, len(nums)): |
| 14 | + comb.append(nums[i]) |
| 15 | + backtrack(i + 1, comb) |
| 16 | + comb.pop() |
| 17 | + |
| 18 | + backtrack(0, []) |
| 19 | + return result |
| 20 | + |
| 21 | +# time complexity: O(n*2^n) |
| 22 | +# space complexity: O(n*2^n) |
| 23 | +class Solution: |
| 24 | + def subsets(self, nums): |
| 25 | + result = [[]] |
| 26 | + for num in nums: |
| 27 | + newSubsets = [] |
| 28 | + for curr in result: |
| 29 | + temp = curr.copy() |
| 30 | + temp.append(num) |
| 31 | + newSubsets.append(temp) |
| 32 | + for curr in newSubsets: |
| 33 | + result.append(curr) |
| 34 | + return result |
| 35 | + |
| 36 | +# time complexity: O(n*2^n) |
| 37 | +# space complexity: O(n) |
| 38 | +class Solution: |
| 39 | + def subsets(self, nums: List[int]) -> List[List[int]]: |
| 40 | + n = len(nums) |
| 41 | + result = [] |
| 42 | + |
| 43 | + for i in range(2**n, 2 ** (n + 1)): |
| 44 | + # generate bitmask, from 0..00 to 1..11 |
| 45 | + bitmask = bin(i)[3:] |
| 46 | + # append subset corresponding to that bitmask |
| 47 | + result.append([nums[j] for j in range(n) if bitmask[j] == "1"]) |
| 48 | + |
| 49 | + return result |
| 50 | + |
| 51 | + |
| 52 | +class Solution: |
| 53 | + def subsets(self, nums: List[int]) -> List[List[int]]: |
| 54 | + result = list(chain.from_iterable(combinations(nums, r) |
| 55 | + for r in range(len(nums)+1))) |
| 56 | + for i, item in enumerate(result): |
| 57 | + result[i] = list(item) |
| 58 | + return result |
| 59 | + |
| 60 | + |
| 61 | +class Solution: |
| 62 | + def subsets(self, nums: List[int]) -> List[List[int]]: |
| 63 | + output = [[]] |
| 64 | + for num in nums: |
| 65 | + output += [curr + [num] for curr in output] |
| 66 | + return output |
| 67 | + |
| 68 | + |
| 69 | +nums = [1, 2, 3] |
| 70 | +print(Solution().subsets(nums)) |
| 71 | +nums = [0] |
| 72 | +print(Solution().subsets(nums)) |
0 commit comments