全排列-力扣解题
给定一个没有重复数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
import copy
class Solution:
def permute(self, nums: list) -> list:
result = []
visited = {}
for num in nums:
visited[num] = False
self.dfs(nums, result, visited, [])
return result
def dfs(self, nums:list, result:list, visited:dict, lst:list) -> None:
if len(lst) == len(nums):
result.append(copy.deepcopy(lst))
return
for num in nums:
if not visited[num]:
lst.append(num)
visited[num] = True
self.dfs(nums, result, visited, lst)
lst.pop()
visited[num] = False