I am working on finding all distinct permutations of a list of numbers, but am stuck on the output of my global ans variable. When I print it out, I get the following results as shown below and am not sure why this is happening. As a follow up how should I recursively collect all the answers without using a global variable?
[[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()