当前位置:网站首页>47. Permutations II

47. Permutations II

2022-06-22 12:26:00 Sterben_Da

47. Permutations II

Medium

5716100Add to ListShare

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

Example 1:

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

Example 2:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Constraints:

  • 1 <= nums.length <= 8
  • -10 <= nums[i] <= 10
class Solution:
    def permuteUnique(self, nums: List[int]) -> List[List[int]]:
        """
        解题思路:与 46.Permutations 不同, 因为存在重复的数字
        参考别人的,使用计数器,每次枚举遍历所有key,回溯
        遍历计数器的key确保不会出现重复

        """

        from collections import Counter
        counter = Counter(nums)
        result = []

        def dfs(l: List[int], count=0):
            if count == len(nums):
                result.append(l)
            else:
                for key, c in counter.items():
                    if c > 0:
                        counter[key] -= 1
                        dfs(l + [key], count + 1)
                        counter[key] += 1

        dfs([])
        return result

原网站

版权声明
本文为[Sterben_Da]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Sterben_Da/article/details/125097619