-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubsets
40 lines (36 loc) · 1.8 KB
/
subsets
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
40
def subsets(self, nums):
solution = [[]]
if len(nums) == 0:
return solution
sorted_list = sorted(nums) #to simplify, we sort input array
for k in range(1,len(nums)+1):
init_set,traverse_stack = [i for i in range(k)],[] #note solution here store position index instead of member of input array since input array is not necessarily be [1..n]
last_solution = init_set[:]
solution.append([sorted_list[i] for i in last_solution])
for pos in range(k-1,-1,-1):
traverse_stack.append(pos)
while len(traverse_stack) != 0:
if last_solution[traverse_stack[-1]] + k - traverse_stack[-1] <= len(nums)-1:
while last_solution[traverse_stack[-1]] + k - traverse_stack[-1] <= len(nums)-1:
tpos = traverse_stack[-1]
last_solution[tpos] += 1
for x in range(tpos+1,k):
last_solution[x] = last_solution[x-1] + 1
traverse_stack.append(x)
solution.append([sorted_list[i] for i in last_solution])
else:
traverse_stack.pop()
return solution
#see comments
recursive version:
def subsets_recursive(self, nums, solution_set, combo, x):
if combo not in solution_set:
solution_set.append(combo[:])
for element in range(x,len(nums)):
combo.append(nums[element])
self.subsets_recursive(nums,solution_set,combo,element+1)
combo.pop()
def subsets(self, nums):
solution_set, combo = [], []
self.subsets_recursive(nums,solution_set,combo,0)
return solution_set