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

Function permute_backtrack

data_structures/arrays/permutations.py:21–40  ·  view source on GitHub ↗

Return all permutations of the given list. >>> permute_backtrack([1, 2, 3]) [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]

(nums: list[int])

Source from the content-addressed store, hash-verified

19
20
21def permute_backtrack(nums: list[int]) -> list[list[int]]:
22 """
23 Return all permutations of the given list.
24
25 >>> permute_backtrack([1, 2, 3])
26 [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 2, 1], [3, 1, 2]]
27 """
28
29 def backtrack(start: int) -> None:
30 if start == len(nums) - 1:
31 output.append(nums[:])
32 else:
33 for i in range(start, len(nums)):
34 nums[start], nums[i] = nums[i], nums[start]
35 backtrack(start + 1)
36 nums[start], nums[i] = nums[i], nums[start] # backtrack
37
38 output: list[list[int]] = []
39 backtrack(0)
40 return output
41
42
43if __name__ == "__main__":

Callers 1

permutations.pyFile · 0.85

Calls 1

backtrackFunction · 0.70

Tested by

no test coverage detected