给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
思路1 : 库函数
Python3 itertools 文档 :https://docs.python.org/3/library/itertools.html#itertools.permutations
一行代码:
def permute(self, nums: List[int]) -> List[List[int]]:
return list(itertools.permutations(nums))
思路2 : 回溯算法
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
def backtrack(nums_temp, tmp):
if not nums_temp:
res.append(tmp)
return
for i in range(len(nums_temp)):
backtrack(nums_temp[:i] + nums_temp[i+1:], tmp + [nums_temp[i]])
backtrack(nums, [])
return res
思路3:深度优先搜索
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
if len(nums) == 0:
return []
if len(nums) == 1:
return [nums]
path = []
res = []
self.dfs(nums, path, res)
return res
def dfs(self, nums, path, res):
if len(path) == len(nums):
res.append(path)
return
for i in nums:
if i not in path:
path.append(i)
b=path[:]
self.dfs(nums, b, res)
path.pop()