-
Notifications
You must be signed in to change notification settings - Fork 0
/
all_possible_subsets.py
49 lines (41 loc) · 1.05 KB
/
all_possible_subsets.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
39
40
41
42
43
44
45
46
47
48
49
"""
Given a set of distinct integers, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
Also, the subsets should be sorted in ascending ( lexicographic ) order.
The list is not necessarily sorted.
Example :
If S = [1,2,3], a solution is:
[
[],
[1],
[1, 2],
[1, 2, 3],
[1, 3],
[2],
[2, 3],
[3],
]
"""
def subsets_wrong(arr):
result = [[]]
for i, num in enumerate(arr):
new_results = []
for j, subset in enumerate(result):
# wrong bc im assigning a reference to the original object,
# not copying it
tmp = subset
tmp.append(num)
new_results.append(tmp)
result.extend(new_results)
return result
def subsets(arr):
result = [[]]
for i, num in enumerate(arr):
new_results = []
for j, subset in enumerate(result):
new_results.append(subset + [num])
result.extend(new_results)
return result
print subsets([1, 2, 3])