leetcode - 47.Permutations II

在这里插入图片描述

无重全排列递归解法
class Solution:
    def permute(self, nums):
        res= []
        self.recur([],nums,res)
        return res
    def recur(self,head,tail,res):
        if len(tail)<=1:
            res.append(head+tail)
            return
        for v in tail:  
            self.recur(head+[v],[i for i in tail if i!=v],res)
有重全排列递归解法
class Solution:
    def permuteUnique(self, nums):
        res= []
        self.recur([],nums,res)
        return res
    def recur(self,head,tail,res):
        if len(tail)<=1:
            res.append(head+tail)
            return
        r = []
        for i,v in enumerate(tail):
            if v not in r:
                self.recur(head+[v],[tail[j] for j in range(len(tail)) if j!=i],res)
                r.append(v)

简单解法

设计一个列表,每次放入一个数字,将数字可能放的位置全部记录一遍,重复的项只放相同之前的位置,例如【1,2,3…n】,将n+1放入其中,有n+1种放法,若将n放入其中,则只有n种
[1,1,2]>[[1]]>>[[1,1]]==>[[2,1,1],[1,2,1],[1,1,2]]

class Solution:                
    def permuteUnique(self, nums):
        ans = [[]]
        for n in nums:
            new_ans = []
            for l in ans:
                for i in range(len(l)+1):
                    new_ans.append(l[:i]+[n]+l[i:])
                    if i<len(l) and l[i]==n: 
                        break              #handles duplication
            ans = new_ans
        return ans
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值