LeetCode算法题之47. Permutations II(medium)【Python3题解】

探讨LeetCode算法题47.Permutations II的解决策略,针对含有重复元素的数组,提供一种有效的去重方法来生成所有可能的唯一排列。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述:
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]
]

题目大意:

  • 给定一个数组,但是包含重复的数字,返回所有的不重复的排列顺序

解题思路:

  1. 有II,必有I,请看LeetCode算法题之46. Permutations I(medium)【Python3题解】
  2. 看过I后,II的区别只是数组包含了重复的数字,个人想法,简单粗暴,同样是I的思路,最后加上去重的代码即可

少废话,上代码:

class Solution:
    def permuteUnique(self, nums):
        ans = []

        def find(nums=nums, idx=0):
            if idx == len(nums)-1:
                if nums not in ans:#去重代码,只有不在ans中的,才加到里面
                    ans.append(nums)
            else:
                for i in range(idx, len(nums)):
                    nums[i], nums[idx] = nums[idx], nums[i]
                    find(nums[:], idx+1)
        find()

        return ans

运行时间和内存使用:

  • Runtime: 2024 ms, faster than 5.06% of Python3 online submissions for Permutations II.
  • Memory Usage: 14.1 MB, less than 6.67% of Python3 online submissions for Permutations II
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值