回溯法
分别列举出我的代码和官方的代码
应该是一个意思(二者执行速度和内存消耗基本一样)
但是官方的代码更简洁
以下为我的代码(在递归的时候,对reslist和inputlist都进行copy)
class Solution:
def __init__(self):
self.res = []
def permute(self, nums: List[int]) -> List[List[int]]:
if nums != []:
self.qpl(nums,[])
return self.res
def qpl(self,inputlist,reslist):
if inputlist == []:
tempres = []
for each in reslist:
tempres.append(each)
self.res.append(tempres)
else:
for i,value in enumerate(inputlist):
reslist.append(value)
templist = []
for j,each in enumerate(inputlist):
if j != i:
templist.append(each)
self.qpl(templist,reslist)
reslist.pop(-1)
以下为https://leetcode-cn.com/problems/permutations/solution/的实现,好看一些
官方解法可以理解为 不生成新list,只是在原本的list中改变元素顺序
例如,我们一开始将原list输入进函数中,此时起始指针指向元素[0],即我们先以[0]为队首
然后我们对List[1:]开始递归,再将List[1:]中的[0]作为队首
直到递归至以原数组的最后一个元素作为队首的长度为1的子list
我们便得到了第一个结果,即顺序结果
此时函数会跳回到倒数第二个元素
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] = nums[i], nums[first]
n = len(nums)
output = []
backtrack()
return output
融合了上述两种方法的解法
import copy
class Solution:
def __init__(self):
self.res = []
def permute(self, nums: List[int]) -> List[List[int]]:
if nums != []:
length = len(nums)
self.qpl2(nums,0,length)
return self.res
def qpl2(self,inputlist,index,length):
if index == length:
print(inputlist)
templist = copy.deepcopy(inputlist)
self.res.append(templist)
else:
for i in range(index,length):
inputlist[index],inputlist[i] = inputlist[i],inputlist[index]
self.qpl2(inputlist,index + 1,length)
inputlist[index],inputlist[i] = inputlist[i],inputlist[index]