[LeetCode]题解(python):047-Permutations II


题目来源


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)


 1 class Solution(object):
 2     def permuteUnique(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: List[List[int]]
 6         """
 7         nums.sort()
 8         if len(nums) == 1:
 9             return [nums]
10         res = []
11         pre = None
12         for i in range(len(nums)):
13             if nums[i] == pre:
14                 continue
15             pre = nums[i]
16             for j in self.permuteUnique(nums[:i] + nums[i+1:]):
17                 res.append([nums[i]] + j)
18         return res

 

posted @ 2015-12-30 11:33  loadofleaf  Views(271)  Comments(0Edit  收藏  举报