I wrote a recursive permutation generator in python3:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
ret = []
n = len(nums)
def dfs(temp, visited):
if len(temp) == n:
ret.append(temp[:])
return
for i in range(n):
if not visited[i]:
visited[i] = True
temp.append(nums[i])
dfs(temp, visited)
# Cannot be:
# temp = temp[:-1]
del temp[-1]
visited[i] = False
dfs([], [False for _ in range(n)])
return ret
I originally used temp = temp[:-1] after the recursive dfs returned but that does not seem to work. Explicitly using del temp[-1] worked.
I can't figure out why this is the case, could anyway please explain?