47. Permutations II

2019-04-25

47. Permutations II

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

Example:

1
2
3
4
5
6
7
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

Code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if not nums:
return []
nums.sort()
ret = [[]]
for n in nums:
new_ret = []
l = len(ret[-1])
for seq in ret:
for i in range(l, -1, -1):
if i < l and seq[i] == n:
break
new_ret.append(seq[:i] + [n] + seq[i:])
ret = new_ret
return ret
-->