题目
给定一个没有重复数字的序列,返回其所有可能的全排列。
库函数
def permute(self, nums: List[int]) -> List[List[int]]:
# 注意permutations是根据位置进行排列,所以若题目没有"无重复"条件的话需要set先
return list(itertools.permutations(nums, len(nums)))
回溯
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def backtrack(first = 0):
# if all integers are used up
if first == n:
output.append(nums[:])
for i in range(first, n):
# place i-th integer first
# in the current permutation
nums[first], nums[i] = nums[i], nums[first]
# use next integers to complete the permutations
backtrack(first + 1)
# backtrack
nums[first], nums[i] = nums[i], nums[first]
n = len(nums)
output = []
backtrack()
return output