输入一个array,返回这个array中元素的所有排列组合情况。
样例输入:
[1,2,3]
样例输出:
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
Solution
解释部分待续
def getPermutations(array):
permutations_rec =[]
permutations_help(array,[],permutations_rec)
return permutations_rec
def permutations_help(array,currentPermutaion,permutations):
print(f"currentPermutaion{currentPermutaion}")
if not len(array) and len(currentPermutaion):
permutations.append(currentPermutaion)
else:
for i in range(len(array)):
print(f"i = {i}")
new_array = array[:i]+array[i+1 :]
print(f"new_array{new_array}")
new_permutaion = currentPermutaion+[array[i]]
print(f"new_permutaion{new_permutaion}")
permutations_help(new_array,new_permutaion,permutations)
print(getPermutations(array = [1,2,3]))
a = [1,2,3,4,5]
print(a[1:])
### Time: O(n*n!)
### Space: Time: O(n*n!)
output
currentPermutaion[]
i = 0
new_array[2, 3]
new_permutaion[1]
currentPermutaion[1]
i = 0
new_array[3]
new_permutaion[1, 2]
currentPermutaion[1, 2]
i = 0
new_array[]
new_permutaion[1, 2, 3]
currentPermutaion[1, 2, 3]
i = 1
new_array[2]
new_permutaion[1, 3]
currentPermutaion[1, 3]
i = 0
new_array[]
new_permutaion[1, 3, 2]
currentPermutaion[1, 3, 2]
i = 1
new_array[1, 3]
new_permutaion[2]
currentPermutaion[2]
i = 0
new_array[3]
new_permutaion[2, 1]
currentPermutaion[2, 1]
i = 0
new_array[]
new_permutaion[2, 1, 3]
currentPermutaion[2, 1, 3]
i = 1
new_array[1]
new_permutaion[2, 3]
currentPermutaion[2, 3]
i = 0
new_array[]
new_permutaion[2, 3, 1]
currentPermutaion[2, 3, 1]
i = 2
new_array[1, 2]
new_permutaion[3]
currentPermutaion[3]
i = 0
new_array[2]
new_permutaion[3, 1]
currentPermutaion[3, 1]
i = 0
new_array[]
new_permutaion[3, 1, 2]
currentPermutaion[3, 1, 2]
i = 1
new_array[1]
new_permutaion[3, 2]
currentPermutaion[3, 2]
i = 0
new_array[]
new_permutaion[3, 2, 1]
currentPermutaion[3, 2, 1]
[[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
[2, 3, 4, 5]
[Finished in 0.6s]