47. Permutations II

首先是 used记得赋值1,然后清零。
然后是所有重复数字,人为的给个约束,前面的不用,后面的也不能用。
这样化无序为有序。

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        result = []
        used = [0 for _ in range(len(nums))]
        def dfs(start, pathlist):
            if len(pathlist)==len(nums):
                result.append(pathlist[:])
                
            for i in range(len(nums)):
                if used[i]: continue
                    
                # when duplicates, and the first duplicated numbrer is used,
                # we would want to use it.
                # basically "if the previous number is not used, this number should not be used"
                # It's like the first '1' is the leader, it can call all the '1's
                # Gives an internal order among 1s
                if i>0 and nums[i]==nums[i-1] and not used[i-1]: continue
                    
                used[i] = 1
                pathlist.append(nums[i])
                dfs(start+1, pathlist)
                pathlist.pop()
                used[i] = 0
        nums.sort()
        dfs(0, [])
        return result

你可能感兴趣的:(算法题)