I am trying to solve the leetcode 46 problem (https://leetcode.com/problems/permutations/) and I came up with 2 solutions and both appear identical to me, however one of them just returns empty output.
Incorrect Solution
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
self.ans = list()
self.final_length = len(nums)
available_items = nums.copy()
current_items = []
self.solve(available_items,current_items)
return self.ans
def solve(self,available_items,current_items ):
if len(current_items) == self.final_length:
self.ans.append(current_items)
for i in range(len(available_items)):
current_items.append(available_items.pop(i))
self.solve(available_items,current_items)
available_items.insert(i,current_items.pop())
For input [1,2,3] I get [[],[],[],[],[],[],[],[]]
Correct Solution
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
self.ans = list()
self.final_length = len(nums)
available_items = nums.copy()
current_items = []
self.solve(available_items,current_items)
return self.ans
def solve(self,available_items,current_items ):
if len(current_items) == self.final_length:
self.ans.append(current_items)
for i in range(len(available_items)):
self.solve(available_items[:i]+available_items[i+1:],current_items+[available_items[I]])
For input [1,2,3] I get [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
I do not understand what's the difference here in terms of storing answers. Am I missing some basic concept here in Python?