LeetCode:46. Permutations

博客围绕 LeetCode 46 题求数组全排列展开,介绍使用回溯法求解。以 [1,2,3] 为例,说明可先求 [1,2] 全排列,再将 3 插入空隙得到 [1,2,3] 全排列。还给出 Python 代码简单写法,提到 47 题对结果去重即可。

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

LeetCode:46. Permutations

Given a collection of distinct integers, return all possible permutations.

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

就是求一个数组的全排列数组。

思路:回溯法

LeetCode:31. Next Permutation 的暴力求解法中已经实现过全排列的算法。以 [1,2,3] 为例,求[1,2,3] 的全排列,只要求得[1,2]的全排列数组,这里是[[1,2],[2,1]]然后再将3插入到每个数组的空隙,比如[3,1,2],[1,3,2],[1,2,3]。而求[1,2]的全排列也是同理。

Python 代码实现

class Solution:
    def permutePart(self, nums: List[int]) -> List[List[int]]:
        res = []
        l = len(nums)
        if l == 1:
            res.append(nums)
        else:
            lastPermute = self.permutePart(nums[0:l-1])
            if lastPermute is not None:
                for last in lastPermute:
                    if last is not None:
                        ll = len(last)
                        for i in range(ll+1):
                            tmp = last[:]
                            tmp.insert(i,nums[l-1])
                            res.append(tmp)
        return res
        
        
    def permute(self, nums: List[int]) -> List[List[int]]:
        p = self.permutePart(nums)
        return p

对于这种思路,Discuss 中的一种简单写法。

class Solution:
    def permute(self, nums):
        perms = [[]]   
        for n in nums:
            new_perms = []
            for perm in perms:
                for i in range(len(perm)+1):   
                    new_perms.append(perm[:i] + [n] + perm[i:])   ###insert n
            perms = new_perms
        return perms

此外 47. Permutations II 对上面这个结果去重就可以了。


THE END.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值