-
Notifications
You must be signed in to change notification settings - Fork 20
/
subsetsproblem.py
38 lines (29 loc) · 1005 Bytes
/
subsetsproblem.py
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
31
32
33
34
35
36
37
38
'''
Given an integer array nums of unique elements, return all possible subsets (the power set).
The solution set must not contain duplicate subsets. Return the solution in any order.
'''
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = [[]]
for num in nums:
for i in range(len(result)):
result.append(result[i]+[num])
return result
#O (n * 2^n)
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
result = []
subsetCurrent = []
def dfs(index):
#base case
if index >= len(nums):
result.append(subsetCurrent.copy())
return
#include nums[index]
subsetCurrent.append(nums[index])
dfs(index+1)
#don't include nums[index]
subsetCurrent.pop()
dfs(index+1)
dfs(0)
return result