I am working on LeetCode problem 46. Permutations:
Given an array
nums
of distinct integers, return all the possible permutations. You can return the answer in any order.
I thought to solve this using backtracking. My idea is to image this problem as a binary tree and step down a path. When I get to a leaf I pop the visit
array and restore to a new root number.
My code below:
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
perms = []
def dfs(curr, l):
if len(nums) == len(curr):
perms.append([int(i) for i in curr])
return
visit = []
for t in nums:
if str(t) not in curr:
visit.append(t)
dfs(curr + str(l), t)
visit.pop()
return
dfs('', nums[0])
return perms
I get wrong output for the following test case:
nums = [1,2,3]
The expected output is:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
But my code outputs:
[[1,1,2],[1,1,2],[1,1,3],[1,1,3],[1,2,2],[1,2,3],[1,3,2],[1,3,3]]
I don't understand why my output has lists with duplicate ones, even though I check that str(t) not in curr
to avoid that duplicate use of a number.
What am I missing?