forked from shuboc/LeetCode-2
-
Notifications
You must be signed in to change notification settings - Fork 1
/
subsets-ii.py
88 lines (77 loc) · 2.18 KB
/
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
from __future__ import print_function
# Time: O(n * 2^n)
# Space: O(1)
# 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],
# []
# ]
class Solution(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
result = [[]]
previous_size = 0
for i in xrange(len(nums)):
size = len(result)
for j in xrange(size):
# Only union non-duplicate element or new union set.
if i == 0 or nums[i] != nums[i - 1] or j >= previous_size:
result.append(list(result[j]))
result[-1].append(nums[i])
previous_size = size
return result
# Time: O(n * 2^n) ~ O((n * 2^n)^2)
# Space: O(1)
class Solution2(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
i, count = 0, 1 << len(nums)
nums.sort()
while i < count:
cur = []
for j in xrange(len(nums)):
if i & 1 << j:
cur.append(nums[j])
if cur not in result:
result.append(cur)
i += 1
return result
# Time: O(n * 2^n) ~ O((n * 2^n)^2)
# Space: O(1)
class Solution3(object):
def subsetsWithDup(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
result = []
self.subsetsWithDupRecu(result, [], sorted(nums))
return result
def subsetsWithDupRecu(self, result, cur, nums):
if not nums:
if cur not in result:
result.append(cur)
else:
self.subsetsWithDupRecu(result, cur, nums[1:])
self.subsetsWithDupRecu(result, cur + [nums[0]], nums[1:])
if __name__ == "__main__":
print(Solution().subsetsWithDup([1, 2, 2]))