0

Unable to understand where is the bug in this code this is the recursive solution, i've written the same logic in C++ but it's not working in python

 class Solution:
        def permute(self, nums: List[int]) -> List[List[int]]:
            arr = []
            def per(nums,i):
                if i == len(nums)-1:
                    arr.append(nums)
                    return
                for j in range(i,len(nums)):
                    nums[i],nums[j] = nums[j],nums[i]
                    per(nums,i+1)
                    nums[i],nums[j] = nums[j],nums[i]
            per(nums,i=0)
            return arr
    
    #input: nums = [1,2,3]
    #my output: [[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
    #correct output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
  • Hello! Welcome to StackOverflow. Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – Stef Sep 16 '21 at 17:29
  • Quickfix: try replacing `arr.append(nums)` with `arr.append(list(nums))`; this will append *a copy of nums* instead of *the original nums* – Stef Sep 16 '21 at 17:30

1 Answers1

0

The thing is, you are working allways on the same list, oposed to C++, python will not make a new list for each function call, that means you are adding to arr, exactly the same list all the times. As said in the comments you can pass a new list calling the list constructor.

Daniel
  • 131
  • 6