Skip to content

Commit 4a27b54

Browse files
authored
Update permutations.py (TheAlgorithms#8102)
1 parent c93659d commit 4a27b54

File tree

1 file changed

+25
-1
lines changed

1 file changed

+25
-1
lines changed

data_structures/arrays/permutations.py

+25-1
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
def permute(nums: list[int]) -> list[list[int]]:
22
"""
33
Return all permutations.
4-
54
>>> from itertools import permutations
65
>>> numbers= [1,2,3]
76
>>> all(list(nums) in permute(numbers) for nums in permutations(numbers))
@@ -20,7 +19,32 @@ def permute(nums: list[int]) -> list[list[int]]:
2019
return result
2120

2221

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

47+
# use res to print the data in permute2 function
48+
res = permute2([1, 2, 3])
49+
print(res)
2650
doctest.testmod()

0 commit comments

Comments
 (0)