代码改变世界

[LeetCode] 47. Permutations II_Medium tag: DFS, backtracking

2019-05-24 09:35  Johnson_强生仔仔  阅读(248)  评论(0编辑  收藏  举报

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

Example:

Input: [1,1,2]
Output:
[
  [1,1,2],
  [1,2,1],
  [2,1,1]
]

这个题目在[LeetCode] 46. Permutations_Medium tag: DFS, backtracking 的基础上增加了重复的数,那么如果假设重复的数有编号的话,ex [1(1), 1(2), 2], 或者说因为我们的helper实际上做的就是选出nums[i] 然后以它为开头的permutation,所以对于有重复数字的,我们可以就选第一个就好。因此我们先排序nums,然后if i and nums[i] == nums[i - 1]: continue, 跳过重复的,其他的保持跟[LeetCode] 46. Permutations_Medium tag: DFS, backtracking 就好。

时间复杂度 = 方案总数 * 构造方案所需时间

O( n ! * n)

Code:

class Solution:
    def permutations2(self, nums):
        ans = []
        nums.sort()
        def helper(ans, temp, nums):
            if not nums:
                ans.append(temp)
       
for i in range(len(nums)): if i and nums[i] == nums[i - 1]:
            continue helper(ans, temp
+ nums[i], nums[:i] + nums[i + 1:]) helper(ans, [], nums) return ans

 利用python的itertools:

class Solution:
    def permutations2(self, nums):
        return list(set(itertools.permutations(nums)))

 

Update on 08/11/2023, 直接用visited来判断是否是duplicates,但是也是要先sort

class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        ans = []
        nums.sort()
        def helper(nums, ans, temp):
            if not nums:
                ans.append(temp)
            visited = set()
            for i in range(len(nums)):
                if nums[i] not in visited:
                    visited.add(nums[i])
                    helper(nums[:i] + nums[i + 1:], ans, temp + [nums[i]])
        helper(nums, ans, [])
        return ans