Skip to content

Commit a41bf1b

Browse files
committed
Update subsets-ii.py
1 parent 2716a3f commit a41bf1b

File tree

1 file changed

+48
-22
lines changed

1 file changed

+48
-22
lines changed

Python/subsets-ii.py

Lines changed: 48 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Time: O(n * 2^n)
22
# Space: O(1)
3-
#
3+
44
# Given a collection of integers that might contain duplicates, S, return all possible subsets.
55
#
66
# Note:
@@ -17,41 +17,67 @@
1717
# [1,2],
1818
# []
1919
# ]
20-
#
2120

22-
class Solution:
23-
# @param num, a list of integer
24-
# @return a list of lists of integer
25-
def subsetsWithDup(self, S):
21+
class Solution(object):
22+
def subsetsWithDup(self, nums):
23+
"""
24+
:type nums: List[int]
25+
:rtype: List[List[int]]
26+
"""
27+
nums.sort()
28+
result = [[]]
29+
previous_size = 0
30+
for i in xrange(len(nums)):
31+
size = len(result)
32+
for j in xrange(size):
33+
# Only union non-duplicate element or new union set.
34+
if i == 0 or nums[i] != nums[i - 1] or j >= previous_size:
35+
result.append(list(result[j]))
36+
result[-1].append(nums[i])
37+
previous_size = size
38+
return result
39+
40+
41+
class Solution2(object):
42+
def subsetsWithDup(self, nums):
43+
"""
44+
:type nums: List[int]
45+
:rtype: List[List[int]]
46+
"""
2647
result = []
27-
i, count = 0, 1 << len(S)
28-
S = sorted(S)
48+
i, count = 0, 1 << len(nums)
49+
nums.sort()
2950

3051
while i < count:
3152
cur = []
32-
for j in xrange(len(S)):
53+
for j in xrange(len(nums)):
3354
if i & 1 << j:
34-
cur.append(S[j])
55+
cur.append(nums[j])
3556
if cur not in result:
3657
result.append(cur)
3758
i += 1
3859

3960
return result
4061

41-
class Solution2:
42-
# @param num, a list of integer
43-
# @return a list of lists of integer
44-
def subsetsWithDup(self, S):
62+
63+
class Solution3(object):
64+
def subsetsWithDup(self, nums):
65+
"""
66+
:type nums: List[int]
67+
:rtype: List[List[int]]
68+
"""
4569
result = []
46-
self.subsetsWithDupRecu(result, [], sorted(S))
70+
self.subsetsWithDupRecu(result, [], sorted(nums))
4771
return result
4872

49-
def subsetsWithDupRecu(self, result, cur, S):
50-
if len(S) == 0 and cur not in result:
51-
result.append(cur)
52-
elif S:
53-
self.subsetsWithDupRecu(result, cur, S[1:])
54-
self.subsetsWithDupRecu(result, cur + [S[0]], S[1:])
55-
73+
def subsetsWithDupRecu(self, result, cur, nums):
74+
if not nums:
75+
if cur not in result:
76+
result.append(cur)
77+
else:
78+
self.subsetsWithDupRecu(result, cur, nums[1:])
79+
self.subsetsWithDupRecu(result, cur + [nums[0]], nums[1:])
80+
81+
5682
if __name__ == "__main__":
5783
print Solution().subsetsWithDup([1, 2, 2])

0 commit comments

Comments
 (0)