-
Notifications
You must be signed in to change notification settings - Fork 17
/
subsets-ii.py
57 lines (37 loc) · 1.26 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
from typing import List, Set, Tuple
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
nums.sort()
stack: List[int] = []
result: List[List[int]] = []
def dfs(pos: int) -> None:
if pos == len(nums):
result.append(stack.copy())
return
dfs(pos + 1)
start = pos
while pos + 1 < len(nums) and nums[pos] == nums[pos + 1]:
stack.append(nums[pos])
pos += 1
stack.append(nums[pos])
dfs(pos + 1)
for _ in range(pos - start + 1):
stack.pop()
dfs(0)
return result
def subsetsWithDupBruteforce(self, nums: List[int]) -> List[List[int]]:
stack: List[int] = []
result: List[List[int]] = []
seen: Set[Tuple[int, ...]] = set()
def dfs(pos: int) -> None:
if pos == len(nums):
if tuple(sorted(stack)) not in seen:
result.append(stack.copy())
seen.add(tuple(sorted(stack)))
return
dfs(pos + 1)
stack.append(nums[pos])
dfs(pos + 1)
stack.pop()
dfs(0)
return result