Skip to content
31 changes: 20 additions & 11 deletions data_structures/arrays/permutations.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from typing import List

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

remove from typing import List as it is unused , creating pre-commit error.


def permute(nums: list[int]) -> list[list[int]]:
"""
Return all permutations.
Expand All @@ -7,20 +10,26 @@ def permute(nums: list[int]) -> list[list[int]]:
>>> all(list(nums) in permute(numbers) for nums in permutations(numbers))
True
"""
result = []
if len(nums) == 1:
return [nums.copy()]
for _ in range(len(nums)):
n = nums.pop(0)
permutations = permute(nums)
for perm in permutations:
perm.append(n)
result.extend(permutations)
nums.append(n)
return result

def backtrack(first=0):
if first == n:
output.append(nums[:])
for i in range(first, n):
nums[first], nums[i] = nums[i], nums[first]
backtrack(first + 1)
nums[first], nums[i] = nums[i], nums[first]

n = len(nums)
output = []
backtrack()
return output

# return result


if __name__ == "__main__":
import doctest

res = permute([1, 2, 3])
print(res)
doctest.testmod()