47. 全排列 II

47. 全排列 II

題意

給定一個可包含重複數字的序列,返回全部不重複的全排列。web

示例:編程

輸入: [1,1,2]
輸出:
[
[1,1,2],
[1,2,1],
[2,1,1]
]

解題思路

去重的全排列就是從第一個數字起每一個數分別與它後面非重複出現的數字交換。用編程的話描述就是第i個數與第j個數交換時,要求[i,j)中沒有與第j個數相等的數。有兩種方法(1)能夠每次在須要交換時進行順序查找;(2)用哈希表來查重;數組

  1. 回溯:遍歷數組,判斷是否可以交換,再兩兩交換給定對應下標的值;app

  2. 回溯:思想和1同樣;ide

  3. 回溯:遍歷數組,兩兩交換給定對應下標的值,在加入最終結果的時候判斷是否已經存在;spa

  4. 記憶化:經過遍歷當前路徑數組,遍歷當前的路徑數組選擇位置來插入index對應的值實現;code

實現


class Solution(object):
def permuteUnique(self, nums):
       """
      :type nums: List[int]
      :rtype: List[List[int]]
      """

       def swap(start, end):
           nums[start], nums[end] = nums[end], nums[start]

       def can_swap(start, end):
           for i in range(start, end):
               if nums[i] == nums[end]:
                   return False
           return True

       def helper(index):
           if index == len(nums):
               res.append(nums[:])
               return

           for i in range(index, len(nums)):
               # 避免出現相同的子數組
               is_swap = can_swap(index, i)
               if is_swap:
                   print is_swap
                   swap(i, index)
                   helper(index + 1)
                   swap(index, i)

   def permuteUnique(self, nums):
       """
      :type nums: List[int]
      :rtype: List[List[int]]
      """
       def helper(nums, index):
           if index >= len(nums):
               res.append(nums[:])
               return

           for i in range(index, len(nums)):
               if i != index and nums[i] == nums[index]:
                   continue
# 有個問題,爲何在交換以後沒有交換回來,是由於從一開始排序之後,就沒有打算交換回來?
               # 個人猜想是避免再次交換致使的重複的值出現
               nums[i], nums[index] = nums[index], nums[i]
               helper(nums[:], index + 1)

       res = []
       nums.sort()
       helper(nums, 0)
       return res
     
def permuteUnique(self, nums):
       """
      :type nums: List[int]
      :rtype: List[List[int]]
      """
       self.result=[]
       self.helper(nums,0)
       
       return self.result


   def helper(self,nums,i):
       if i ==len(nums)-1:
           self.result.append(nums[:])
       used=set()
       for j in range(i,len(nums)):
           if nums[j] not in used:
               used.add(nums[j])
               nums[i],nums[j]=nums[j],nums[i]
               self.helper(nums[:],i+1)
               nums[i],nums[j]=nums[j],nums[i]
     
def permuteUnique(self, nums):
       """
      :type nums: List[int]
      :rtype: List[List[int]]
      """
       if not nums:
           return []
       
       res = [[]]
       for n in nums:
           temp = []
           for cur in res:
               for i in range(len(cur)+1):
                   temp.append(cur[:i] + [n] + cur[i:])
                   if i < len(cur) and cur[i] == n:  # remove dups
                       break
           res = temp
       return res
相關文章
相關標籤/搜索