MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / permute_recursive

Function permute_recursive

data_structures/arrays/permutations.py:1–18  ·  view source on GitHub ↗

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]]

(nums: list[int])

Source from the content-addressed store, hash-verified

1def permute_recursive(nums: list[int]) -> list[list[int]]:
2 """
3 Return all permutations.
4
5 >>> permute_recursive([1, 2, 3])
6 [[3, 2, 1], [2, 3, 1], [1, 3, 2], [3, 1, 2], [2, 1, 3], [1, 2, 3]]
7 """
8 result: list[list[int]] = []
9 if len(nums) == 0:
10 return [[]]
11 for _ in range(len(nums)):
12 n = nums.pop(0)
13 permutations = permute_recursive(nums.copy())
14 for perm in permutations:
15 perm.append(n)
16 result.extend(permutations)
17 nums.append(n)
18 return result
19
20
21def permute_backtrack(nums: list[int]) -> list[list[int]]:

Callers

nothing calls this directly

Calls 4

copyMethod · 0.80
popMethod · 0.45
appendMethod · 0.45
extendMethod · 0.45

Tested by

no test coverage detected