Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update permutations.py #8102

Merged
merged 11 commits into from
May 31, 2023
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()