题目来源
https://leetcode.com/problems/permutations-ii/
Given a collection of numbers that might contain duplicates, return all possible unique permutations.
For example,[1,1,2]
have the following unique permutations:[1,1,2]
, [1,2,1]
, and [2,1,1]
.
题意分析
Input:list
Output:permutations
Conditions:跟上题类似,但是会有重复的元素
题目思路
直接用上题的做法,首先先排序,然后再遍历的时候用一个pre记录先前位置,如果当前位置与pre相同则跳过
AC代码(Python)
class Solution(object):
def permuteUnique(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
nums.sort()
if len(nums) == 1:
return [nums]
res = []
pre = None
for i in range(len(nums)):
if nums[i] == pre:
continue
pre = nums[i]
for j in self.permuteUnique(nums[:i] + nums[i+1:]):
res.append([nums[i]] + j)
return res