leetcode 47. 全排列 II

https://leetcode-cn.com/probl...python

解題思路

cnts 是每一個數字出現的次數
每次使用一個數字都嘗試使用 1 個、2 個 ... 到用完這個數字。除此以外,不容許有兩次連續選擇相同數字app

代碼

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        import collections
        n = len(nums)
        cnts = collections.Counter(nums)
        nums = list(cnts.keys())
        l = [0] * n
        ans = []
        def dfs(i):
            if i == n:
                ans.append(l[::])
                return
            for num in nums:
                if i > 0 and l[i-1] == num: continue
                oc = cnts[num]
                if oc > 0:
                    j = 0
                    while cnts[num] > 0:
                        cnts[num] -= 1
                        l[i + j] = num
                        dfs(i+j+1)
                        j += 1
                    cnts[num] = oc
        dfs(0)
        return ans

歡迎來個人博客: https://codeplot.top/
個人博客刷題分類:https://codeplot.top/categories/%E5%88%B7%E9%A2%98/code

相關文章
相關標籤/搜索