leetcode-

题目描述:

leetcode-

方法一:回溯

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        #nums = nums.sort()
        n = len(nums)
        res = []
        def backtrack(nums,temp_list,length):
            if length == n and temp_list not in res:
                res.append(temp_list)
            for i in range(len(nums)):
                backtrack(nums[:i] + nums[i + 1:], temp_list + [nums[i]], length + 1)
        backtrack(nums, [], 0)
        return res

另:

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        if not nums:
            return []
        nums.sort()
        
        res = []
        visited = set()
        def backtrack(nums,temp_list,length):
            if length == len(nums) :
                res.append(temp_list)
                return
            for i in range(len(nums)):
                if i in visited or (i > 0 and i - 1 not in visited and nums[i-1] == nums[i]):
                    continue
                visited.add(i)
                backtrack(nums, temp_list + [nums[i]], length + 1)
                visited.remove(i)
        backtrack(nums, [], 0)
        return res

 

上一篇:leetcode-77-组合


下一篇:决策树算法6-案例:泰坦尼克号乘客生存预测