47. Permutations II
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
Example:
Input: [1,1,2]
Output:
[
[1,1,2],
[1,2,1],
[2,1,1]
]
Codeļ¼
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