46. Permutations
Given a collection of distinct integers, return all possible permutations.
回溯法
因为数目可能无限,首先想到递归
递归终止条件返回的数等于列表的数
逐一添加元素至对应位置
class Solution:
def permute(self, nums: List[int]) -> 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