- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path47-Permutations-II.py
42 lines (32 loc) · 818 Bytes
/
47-Permutations-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
'''Leetcode- https://leetcode.com/problems/permutations-ii/'''
'''
Given a collection of numbers, nums, that might contain duplicates, return all possible unique permutations in any order.
Example 1:
Input: nums = [1,1,2]
Output:
[[1,1,2],
[1,2,1],
[2,1,1]]
'''
defpermuteUnique(nums):
result= []
perms= []
count= {n:0forninnums}
forninnums:
count[n] +=1
defdfs():
iflen(perms) ==len(nums):
result.append(perms.copy())
return
fornincount:
ifcount[n] >0:
perms.append(n)
count[n]-=1
dfs()
count[n] +=1
perms.pop()
dfs()
returnresult
print(permuteUnique([1,1,2])) #[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
#T:O(n.2^n)
#S:O(n)