forked from algorhythms/LeetCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
090 Subsets II.py
43 lines (38 loc) · 1.02 KB
/
090 Subsets II.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
"""
Given a collection of integers that might contain duplicates, S, return all possible subsets.
Note:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
For example,
If S = [1,2,2], a solution is:
[
[2],
[1],
[1,2,2],
[2,2],
[1,2],
[]
]
"""
__author__ = 'Danyang'
class Solution:
def subsetsWithDup(self, S):
"""
dfs
notice the skipping
:param S: a list of integer
:return: a list of lists of integer
"""
S.sort()
result = []
self.get_subset(S, [], result)
return result
def get_subset(self, S, current, result):
result.append(current)
for ind, val in enumerate(S):
# JUMP, avoid duplicates
if ind-1>=0 and val==S[ind-1]: # ensure uni-direction
continue
self.get_subset(S[ind+1:], current+[val], result)
if __name__=="__main__":
print Solution().subsetsWithDup([1, 2, 3])