LC 47重复全排列

剪枝条件这里,vsd[i-1]=0的意思是如果前一个重复元素是刚被用完撤销,那么就不在使用避免重复。

class Solution(object):
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        nums.sort()
        res = []
        vsd = [0]*len(nums)
        sol = []
        def backtrack(nums, res, sol, vsd):
            if len(nums) == len(sol):
                res.append(sol[:])
            for i in range(len(nums)):
                if vsd[i] == 1:
                    continue
                if i > 0 and nums[i] == nums[i-1] and vsd[i-1] == 0:
                    continue
                vsd[i] = 1
                sol.append(nums[i])
                backtrack(nums, res, sol, vsd)
                vsd[i] = 0
                sol.pop()
        backtrack(nums, res, sol, vsd)
        return res
递归set去重,看到某大佬的
```python
class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        ans =[]
        visted = []
        def dfs(nums, path):
            if not nums:
                ans.append(path)
                return
            temp = list(set(nums))
            for idx,i in enumerate(temp):
                nums.remove(i)
                dfs(nums, path + [i])
                nums.append(i)
        dfs(nums,[])
        return ans

你可能感兴趣的:(LC回溯,leetcode,算法,职场和发展)