给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
输入: [1,2,3]
输出:
[
[1,2,3],
[1,3,2],
[2,1,3],
[2,3,1],
[3,1,2],
[3,2,1]
]
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
nums.sort()
self.res = []
check = [0 for i in range(len(nums))]
self.backtrack([], nums, check)
return self.res
def backtrack(self, sol, nums, check):
if len(sol) == len(nums):
self.res.append(sol)
return
for i in range(len(nums)):
if check[i] == 1:
continue
#if i > 0 and nums[i] == nums[i-1] and check[i-1] == 0:
# continue
check[i] = 1
self.backtrack(sol+[nums[i]], nums, check)
check[i] = 0
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.dfs(0, res, nums)
return res
def dfs(self, first, res, nums):
# 所有数都填完了
if first == len(nums):
res.append(nums[:])
for i in range(first, len(nums)):
# 动态维护数组
nums[first], nums[i] = nums[i], nums[first]
# 继续递归填下一个数
self.dfs(first + 1, res, nums)
# 撤销操作
nums[first], nums[i] = nums[i], nums[first]