0

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()
user6235442
  • 136
  • 7
  • 1
    `global ans` and `self.ans` are two entirely independent variables. You never use `ans` in your code. – Martijn Pieters Jan 19 '20 at 14:23
  • What you have is a *mutable class attribute*. See the duplicate on how to avoid this issue. You can safely remove `global ans`, it's not doing anything in your code. – Martijn Pieters Jan 19 '20 at 14:26

0 Answers0