I was solving this leetcode permutation problem and came across an error that am getting n empty lists inside my returned list which suppose to print different permutations of the given list
getting output => [[], [], [], [], [], []]
Expected output=> [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
def permute(nums):
l=[]
s=list()
ans=[]
return helper(nums,s,l)
def helper(nums,s,l):
if not nums:
print(l)
s.append(l)
else:
for i in range(len(nums)):
c=nums[i]
l.append(c)
nums.pop(i)
helper(nums,s,l)
nums.insert(i,c)
l.pop()
return s
print(permute([1,2,3]))
You should do s.append(l.copy())
because otherwise you pop all values from the same list l
, that's why the result consists of empty lists.