一、题目
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [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)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。