Q47 - Medium - 全排列 II

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

示例:

输入: [1,1,2]
输出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

import copy
class Solution:
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        res = []
        nums.sort()
        self.back_track(res, nums, 0)
        return res
    
    def back_track(self, res, nums, n):
        nums = copy.deepcopy(nums)
        
        if n == len(nums)-1:
            temp = copy.deepcopy(nums)
            res.append(temp)
        else:
            for i in range(n, len(nums)):
                if i != n and nums[i] == nums[n]:
                    continue
                nums[n], nums[i] = nums[i], nums[n]
                self.back_track(res, nums, n+1)

你可能感兴趣的:(Q47 - Medium - 全排列 II)