-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path47-Permutations-II.py
More file actions
42 lines (32 loc) · 818 Bytes
/
47-Permutations-II.py
File metadata and controls
42 lines (32 loc) · 818 Bytes
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]]
'''
def permuteUnique(nums):
result = []
perms = []
count = {n:0 for n in nums}
for n in nums:
count[n] += 1
def dfs():
if len(perms) == len(nums):
result.append(perms.copy())
return
for n in count:
if count[n] > 0:
perms.append(n)
count[n]-=1
dfs()
count[n] += 1
perms.pop()
dfs()
return result
print(permuteUnique([1,1,2])) #[[1, 1, 2], [1, 2, 1], [2, 1, 1]]
#T:O(n.2^n)
#S:O(n)