Permutations ii

題目描述

Given a list of numbers with duplicate number in it. Find all unique permutations.

Example
For numbers [1,2,2] the unique permutations are:

[
  [1,2,2],
  [2,1,2],
  [2,2,1]
]

難點(diǎn)

這個(gè)題的難點(diǎn)和subsets ii 基本一樣,就是如何去重
原則就是在使用2(2)時(shí), 2(1)必然已經(jīng)使用了

解決辦法:

利用一個(gè)used數(shù)組記錄數(shù)字的使用情況
當(dāng)遇到2(2)時(shí),如果2(1)使用過了,就可以用
否則,跳過這個(gè)2(2)

class Solution(object):
    def permuteUnique(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        if not nums:
            return [[]]
        
        nums.sort()  # sort
        self. result = []
        used = [0] * len(nums)
        self.dfs(nums, used, [])
        return self.result
    
    def dfs(self, nums, used, path):
        if len(nums) == len(path):
            self.result.append(list(path))
            return
        
        for i in range(len(nums)):
            if i != 0 and nums[i] == nums[i-1]:  # 遇到2(2)
                if not used[i-1]:  # 因?yàn)?(1)沒有使用,所以跳過2(2)
                    continue
            if not used[i]:
                used[i] = 1
                path.append(nums[i])
                self.dfs(nums, used, path)
                path.pop()
                used[i] = 0
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容