I working on this problem on leetcode:
Given a collection of distinct integers, return all possible permutations.
If I iteratively print my results I get the correct values. As soon as I add it to a list the results are incorrect. What is happening?
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 1:
return nums
permutations = list()
import math
max_swaps = math.factorial(len(nums))
pair = [0,1]
for i in range(max_swaps):
if pair[1] == len(nums):
pair[0] = 0
pair[1] = 1
p = self.swap(nums, pair[0], pair[1])
print("Adding %s to the list" % p)
permutations.append(p)
pair[0] += 1
pair[1] += 1
return permutations
def swap(self, nums, index1, index2):
tmp = nums[index2]
nums[index2] = nums[index1]
nums[index1] = tmp
return nums
I should get:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
But instead I get:
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]