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

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 就好。

Code:

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

 

上一篇:LeetCode应该怎么刷


下一篇:[LeetCode] 75. Sort Colors_Medium tag: Two pointers