列表arr =[1,2,3]输出其全排列。
采取递归推导的方法来实现。
def perm(arr):
"""实现全排列"""
length = len(arr)
if length == 1: # 递归出口
return [arr]
result = [] # 存储结果
fixed = arr[0]
rest = arr[1:]
for _arr in perm(rest): # 遍历上层的每一个结果
for i in range(0, length): # 插入每一个位置得到新序列
new_rest = _arr.copy() # 需要复制一份
new_rest.insert(i, fixed)
result.append(new_rest)
return result
if __name__ == ‘__main__‘:
r = perm([1,2,3])
for i in r:
print(i)
输出结果
[1, 2, 3]
[2, 1, 3]
[2, 3, 1]
[1, 3, 2]
[3, 1, 2]
[3, 2, 1]
原文:https://www.cnblogs.com/superhin/p/13052312.html