47. Permutations II (全排列有重复的元素)

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:

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

 

1. if i > 0 and nums[i] == nums[i-1] and check[i-1] == 0
灰色为剪枝部分,蓝色为答案部分:

 


2. if i > 0 and nums[i] == nums[i-1] and check[i-1] == 1
灰色为剪枝部分,蓝色为答案部分:

 


能够明显发现第一种能够提前剪枝,减少计算步骤和搜索次数,并且第一种选择了重复元素的第一个,而第二种选择了重复元素的最后一个,虽然答案都相同,我们成年人当然是要选效率更高一些的那一种对吧~

 

class Solution:
    def __init__(self):
        self.res = []
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        
        def dfs(path,nums,level,used):
            if len(path) > len(nums):
                return
            if len(path) == len(nums):
                self.res.append(path.copy())
             
            for i in range(0,len(nums)):
                if i >=1 and nums[i] == nums[i-1] and  used[i-1]:
                    continue
                if used[i]:
                    continue
                path.append(nums[i])
                used[i] = True
                dfs(path,nums,i,used)
                path.pop()
                used[i] = False
        used = [False] * len(nums)  
        used_list = []
        nums = sorted(nums) 
        dfs([],nums,0,used)
        return self.res

 



与上一题不同,就是在19行加个判断即可。
 1 class Solution(object):
 2     def __init__(self):
 3         self.res = []
 4 
 5     def permuteUnique(self, nums):
 6         """
 7         :type nums: List[int]
 8         :rtype: List[List[int]]
 9         """
10         self.help(nums, 0, len(nums))
11 
12         return self.res
13 
14     def help(self, a, lo, hi):
15         if(lo == hi):
16             self.res.append(a[0:hi])
17         for i in range(lo, hi):
18             #判断 i 是否已经在当过头元素了
19             if a[i] not in a[lo:i]:
20                 self.swap(a, i, lo)
21                 self.help(a, lo + 1, hi)
22                 self.swap(a, i, lo)
23     def swap(self, a, i, j):
24         temp = a[i]
25         a[i] = a[j]
26         a[j] = temp

 

posted @ 2018-02-14 19:57  乐乐章  阅读(168)  评论(0编辑  收藏  举报