0

I am trying to solve this problem of finding the permutation of a given list using the code below. But, the list, final keeps appending the same thing again and again. It should return [[1,2,3],[2,1,3],[2,3,1],[1,3,2],[3,1,2],[3,2,1]] but instead it returns [[1,2,3],[1,2,3], [1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]. I have been trying to fix this for a while now and would really appreciate your help.

class Solution(object):
    def permute(self, nums):
        """
        :type nums: List[int]
        :rtype: List[List[int]]
        """
        self.final = []
        l = 0 
        r = len(nums) -1 
        self.permutation(nums, l, r)
        return self.final

    def permutation(self, nums, l, r):
        if l == r:
            self.final.append(nums)
            # print(nums)
            print(self.final)
        else:
            for i in range(r+1):
                nums[l], nums[i] = nums[i], nums[l]
                self.permutation(nums, l+1, r)
                nums[l], nums[i] = nums[i], nums[l]

A = Solution()
A.permute(['1','2','3'])
JJ123
  • 573
  • 1
  • 4
  • 18

1 Answers1

3

you change your list in-place instead of creating a new list every time. your final list contains references to the same list in the end.

a fix for that is to wrirte

def permutation(self, nums, l, r):
    if l == r:
        self.final.append(nums.copy())
        # instead of self.final.append(nums)

note: itertools.permutations would do that job for you.

this post might help understand what is going on here.

and as mentioned in the comment: you still do not get all the permutations. this might work for you:

def permutation(self, nums, k):
    r = [[]]
    for i in range(k):
        r = [[a] + b for a in nums for b in r if a not in b]
    self.final = r
hiro protagonist
  • 44,693
  • 14
  • 86
  • 111