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'])