力扣刷题Day 60:全排列(46)

1.题目描述

2.思路

方法1:用Python自带的全排列函数itertools.permutations()。

方法2:参考Krahets佬的DFS回溯方法,先固定第1位元素,再固定第2位元素······固定到第n位元素时将当前序列加入结果列表,nums = [1, 2, 3]的情况分析见下图。

3.代码(Python3)

方法1:

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res = []
        for permutation in itertools.permutations(nums):
            res.append(permutation)
        return res

方法2:

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        def dfs(fixed):
            print(fixed)
            if fixed == len(nums) - 1:
                # 将当前list的浅拷贝加入res(否则传入原nums的引用)
                res.append(list(nums))
                return
            for i in range(fixed, len(nums)):
                nums[fixed], nums[i] = nums[i], nums[fixed]
                dfs(fixed + 1)
                nums[fixed], nums[i] = nums[i], nums[fixed]

        res = []
        dfs(0)
        return res

4.执行情况

方法1:

方法2:

5.感想

Python的内置函数真的好强大,但是写算法题的时候还是少用吧,还是多磨练磨练自己。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值