Skip to content

Commit d9d73d9

Browse files
authored
Update all_permutations.py
1 parent 2a9cb48 commit d9d73d9

File tree

1 file changed

+41
-9
lines changed

1 file changed

+41
-9
lines changed
Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,45 @@
1-
def all_permutations(input_list):
2-
def _all_permutations(input_list, output_list):
3-
if len(output_list) == len(input_list):
4-
result.append(output_list)
1+
from typing import Any, List
2+
import itertools
3+
4+
5+
def all_permutations_itertools(input_list: List[Any]) -> List[List[Any]]:
6+
"""
7+
Return all permutations of input_list using itertools.permutations,
8+
converted into lists.
9+
10+
Time complexity:
11+
O(n! * n) where n = len(input_list). itertools.permutations generates each
12+
of the n! permutations in O(1) amortized time, but converting each tuple to a list
13+
costs O(n), so the overall complexity is O(n! * n).
14+
"""
15+
return [list(p) for p in itertools.permutations(input_list)]
16+
17+
18+
def all_permutations_backtracking(input_list: List[Any]) -> List[List[Any]]:
19+
"""
20+
Return all permutations of input_list using in-place backtracking.
21+
22+
Time complexity:
23+
O(n! * n) where n = len(input_list).
24+
We generate n! permutations, and each time we reach a full permutation,
25+
we append a copy of length-n list (O(n) copy cost). Swapping operations
26+
also contribute lower-order overhead but do not change the factorial growth.
27+
"""
28+
29+
def _backtrack(start_index: int):
30+
# If we have fixed positions up to the end, record a copy of the current list
31+
if start_index == n:
32+
result.append(input_list.copy())
533
return
634

7-
for element in input_list:
8-
if element not in output_list:
9-
_all_permutations(input_list, output_list + [element])
35+
for i in range(start_index, n):
36+
# Swap element i into the 'start_index' position
37+
input_list[start_index], input_list[i] = input_list[i], input_list[start_index]
38+
_backtrack(start_index + 1)
39+
# Swap back to restore original order before the next iteration
40+
input_list[start_index], input_list[i] = input_list[i], input_list[start_index]
1041

11-
result = []
12-
_all_permutations(input_list, [])
42+
n = len(input_list)
43+
result: List[List[Any]] = []
44+
_backtrack(0)
1345
return result

0 commit comments

Comments
 (0)