我正在努力寻找数字列表的所有不同排列,但仍停留在全局ans变量的输出上。当我将其打印出来时,会得到如下所示的结果,并且不确定为什么会这样。作为后续,我应该如何在不使用全局变量的情况下递归收集所有答案?
[[1, 2, 3]],
[[1, 3, 2], [1, 3, 2]],
[[2, 1, 3], [2, 1, 3], [2, 1, 3]],
[[2, 3, 1], [2, 3, 1], [2, 3, 1], [2, 3, 1]],
[[3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2], [3, 1, 2]],
[[3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1], [3, 2, 1]]
from copy import deepcopy
class Solution:
ans = []
def permute(self, nums: List[int]) -> List[List[int]]:
if nums == None:
return None
self.helper(nums, [])
return self.ans
def helper(self, rem, acc):
global ans
rem_cpy = deepcopy(rem)
if len(rem) == 0:
self.ans.append(acc)
print(self.ans)
return
for i in range(len(rem_cpy)):
acc.append(rem_cpy[i])
rem = rem_cpy[:i] + rem_cpy[i+1:]
self.helper(rem, acc)
acc.pop()