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的内置函数真的好强大,但是写算法题的时候还是少用吧,还是多磨练磨练自己。