I am working on LeetCode problem 46. Permutations:
Given an array
numsof 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?
dfs(curr + str(l), t)has no effect on the localvisit, because each call to a function (including recursive calls, which are not in any way special) has its own local variables, andvisitis local. Please see the linked duplicate for details (the problem described is slightly different, but the cause and solution are the same). There are several other typos and other such minor issues in the code; but we do not provide a debugging service; questions are supposed to be about one problem.Noneis intended. They rely on the side effect of populatingperms, and so the return value of the recursive function is not relevant here. Also thevisitlist you refer to is irrelevant. The code doesn't rely on it, so it has no positive nor negative effect on the algorithm, which relies oncurrfor the "visited" behaviour.