0
class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        res = []
        length = len(nums) - 1
        def dfs(nums, l):
            # base case
            if l == length:
                res.append(nums)
            for i in range(l, length):
              # swap
              temp = nums[l]
              nums[l] = nums[i]
              nums[i] = temp

              dfs(nums, l+1)

              # backtrack
              temp = nums[l]
              nums[l] = nums[i]
              nums[i] = temp
            return 
        dfs(nums, 0)
        return res

The output for [1,2,3] is a list of lists where each element is itself [1,2,3] I don't understand.

  • 1
    It looks like you might be mutating the same `nums` list each time instead of creating a new list for each permutation. – Samwise May 21 '23 at 22:50
  • @MichaelButscher yeah that answers my question but why do I feel like this should work? What is wrong with mutating the list each recursive call ... since I'm backtracking and returning list to original position and saving state when i == length – peter todds May 21 '23 at 23:00
  • 3
    That isn't wrong but storing a reference to the same list object in `res` again and again is. Replace `res.append(nums)` by `res.append(nums[:])` to append a copy. – Michael Butscher May 21 '23 at 23:13
  • @MichaelButscher got it now thanks for your explanation., Here I thought I knew Python :( – peter todds May 21 '23 at 23:18
  • Using the debugging tips from [this article](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) will help you understand in more detail what is happening in your original code. – Code-Apprentice May 21 '23 at 23:18

0 Answers0