Closed
Description
What would you like to share?
Your code looks mostly correct, but there's one issue in the permute_recursive
function due to the modification of the nums
list. Lists in Python are mutable, and when you use nums.pop(0)
, it modifies the original nums
list. This can lead to incorrect results and even an infinite loop.
To fix this, you should pass a copy of the nums
list to the recursive function. Here's the corrected permute_recursive
function:
def permute_recursive(nums: list[int]) -> list[list[int]]:
"""
Return all permutations.
>>> permute_recursive([1, 2, 3])
[[3, 2, 1], [2, 3, 1], [1, 3, 2], [3, 1, 2], [2, 1, 3], [1, 2, 3]]
"""
result: list[list[int]] = []
if len(nums) == 0:
return [[]]
for _ in range(len(nums)):
n = nums.pop(0)
permutations = permute_recursive(nums[:]) # Make a copy of nums
for perm in permutations:
perm.append(n)
result.extend(permutations)
nums.append(n)
return result
With this modification, your code should work correctly for both `permute_recursive` and `permute_backtrack`.
### Additional information
_No response_