I have a question regardng this LeetCode question: 46. Permutations. The following Python solution is very efficient in terms of both runtime and memory usage:
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
def backtrack(arr, cur):
if not arr:
final.append(cur)
return
for i in range(len(arr)):
backtrack(arr[:i] + arr[i+1:], cur + [arr[i]])
final = list()
backtrack(nums, list())
return final
However, in backtrack(arr[:i] + arr[i+1:], cur + [arr[i]])
Python seems to allocate new memory via slicing and concatenation at every level of the recursion. The C++ best practice is different and swaps items in the vector through the backtracking rather than creating a new vector. Is there any optimization Python is doing in the background so that new memory is not allocated at every recursion level? I'm a bit confused here.