leetcode-47 全排列

leetcode-47 全排列

题目描述:

给定一个可包含重复数字的序列,返回所有不重复的全排列。

使用库函数:

from itertools import permutations
class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        res = set(permutations(nums,len(nums)))
        return [list(v) for v in res]

先找出所有的组合,再set

from itertools import permutations
class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        def perm(begin,end,nums):
            if begin == end:
                res.append(nums[:])
            else:
                j = begin
                for i in range(begin,end):
                    nums[i],nums[j] = nums[j],nums[i]
                    perm(begin+1,end,nums)
                    nums[i],nums[j] = nums[j],nums[i]
        res = []
        perm(0,len(nums),nums)
        res = set([tuple(v) for v in res])
        return [list(v) for v in res]

再放入的时候判断,实际上效率更低

from itertools import permutations
class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        def perm(begin,end,nums):
            if begin == end:
                if nums not in res:
                    res.append(nums[:])
            else:
                j = begin
                for i in range(begin,end):
                    nums[i],nums[j] = nums[j],nums[i]
                    perm(begin+1,end,nums)
                    nums[i],nums[j] = nums[j],nums[i]
        res = []
        perm(0,len(nums),nums)
        return res

解法三

from itertools import permutations
class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        def perm(nums,tmp):
            if len(nums) == 0:
                res.append(tmp[:])
            for i in range(len(nums)):
                if i > 0 and nums[i] == nums[i-1]:
                    continue
                perm(nums[:i]+nums[i+1:],tmp+[nums[i]])
        res = []
        nums.sort()
        perm(nums,[])
        return res
posted @ 2019-08-01 23:22  静_渊  阅读(157)  评论(0编辑  收藏  举报