-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetcode Problem 78 Subsets.txt
More file actions
39 lines (30 loc) · 955 Bytes
/
Leetcode Problem 78 Subsets.txt
File metadata and controls
39 lines (30 loc) · 955 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
31
32
33
34
35
36
37
38
39
78. Subsets
Given a set of distinct integers, nums, return all possible subsets (the power set).
Note: The solution set must not contain duplicate subsets.
Example:
Input: nums = [1,2,3]
Output:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Hint to solve: Use recursion with backtracking(popping the elements)
class Solution:
def generateSubsetsRecursive(self, currentIndex, currentSubset, nums):
#print('currentIndex: ', currentIndex, ' currentSubset', currentSubset)
temp = currentSubset.copy()
self.result.append(temp)
for i in range(currentIndex, len(nums)):
currentSubset.append(nums[i])
self.generateSubsetsRecursive(i+1, currentSubset, nums)
currentSubset.pop()
def subsets(self, nums: List[int]) -> List[List[int]]:
self.result = []
self.generateSubsetsRecursive(0,[],nums)
return self.result