***【LeetCode 46】全排列(Python)

本文深入讲解了如何使用深度优先搜索(DFS)和回溯法解决全排列问题,提供了Python代码实现,并介绍了Python自带的itertools.permutations库函数,用于快速生成序列的所有可能排列。

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

一、题目
给定一个 没有重复 数字的序列,返回其所有可能的全排列。

示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]

二、思路
DFS(深度优先搜索)+回溯:难点在于对回溯的理解与运用。很多类似的题都可以使用回溯的通用解法,下面的代码展示的也是通用解法。至于理解,建议大家去看一下这个文章
超强gif助你理解使用“4种”方法求解本题)
,里面的动图很好的解释了这种方法。

这种方法由于常见,常用,所以即使理解不了也建议背会。以备不时之需!!!

三、代码

from typing import List

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res=[]
        tem=[]
        def backtrack(nums,tem):
            if nums==[]:
                if tem not in res:
                    res.append(tem[:])
            else:
                for i in range(len(nums)):
                    tem.append(nums[i])
                    backtrack(nums[0:i]+nums[i+1:],tem)
            if tem==[]:
                return 0
            tem.pop()
        backtrack(nums,tem)
        return res


if __name__ == '__main__':
    nums = [1, 2, 3]
    solution = Solution()
    res = solution.permute(nums)
    print(res)
    

四、其他方法
python有自带的库可以直接生成全排列,了解一下做参考,但没有学习意义。这个方法我此前没有接触过。
itertools.permutations

product 笛卡尔积  (有放回抽样排列)
permutations 排列  (不放回抽样排列)
combinations 组合,没有重复  (不放回抽样组合)
combinations_with_replacement 组合,有重复  (有放回抽样组合)

def permute(self, nums: List[int]) -> List[List[int]]:
        return list(itertools.permutations(nums))

作者:chun-meng-da-xiao-yang
链接:https://leetcode-cn.com/problems/permutations/solution/chao-qiang-gifzhu-ni-li-jie-shi-yong-4chong-fang-f/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值