forked from Kyrylo-Ktl/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubsets.py
More file actions
30 lines (23 loc) · 756 Bytes
/
Subsets.py
File metadata and controls
30 lines (23 loc) · 756 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from typing import Generator, List
class Solution:
"""
Time: O(2^n)
Memory: O(n)
"""
def subsets(self, nums: List[int]) -> Generator:
return self._subsets_generator(nums, 0, [])
@classmethod
def _subsets_generator(cls, nums: List[int], i: int, acc: List[int]) -> Generator:
if i < len(nums):
yield from cls._subsets_generator(nums, i + 1, acc + [nums[i]])
yield from cls._subsets_generator(nums, i + 1, acc)
else:
yield acc
class Solution:
"""
Time: O(n*2^n)
Memory: O(1)
"""
def subsets(self, nums: List[int]) -> List[List[int]]:
n = len(nums)
return [[nums[i] for i in range(n) if (n >> i) & 1] for n in range(1 << n)]