这里有一个回溯函数,使用第一个整数的索引作为参数 backtrack(first)。
1,如果第一个整数有索引 n,意味着当前排列已完成。
2,遍历索引 first 到索引 n-1 的所有整数 ,则:
在排列中放置第 i 个整数,即 swap(nums[first], nums[i])
继续生成从第 i 个整数开始的所有排列:backtrack(first +1)
现在回溯,通过 swap(nums[first], nums[i]) 还原。
class Solution:
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] =