码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2015-12-30 13:20:32      阅读:307      评论:0      收藏:0      [点我收藏+]

标签:


题目来源


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

 

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

标签:

原文地址:http://www.cnblogs.com/loadofleaf/p/5088266.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!