以下是对其工作原理的描述:
remove the first element
get all permutations of the remaining elements (recursively)
for each position in each permutation
insert the first element at that position in that permutation
使用示例
permutations of [a, b, c]
remove a
permutations of [b, c]
remove b
permutations of [c]
remove c
permutations of []
= [[]]
for each, insert c in each position
=[[c]]
for each, insert b in each position
=[[b,c], [c,b]]
for each, insert a in each position
= [[a,b,c], [a,c,b], [b,a,c], [c,a,b], [b,c,a], [c,b,a]]
计算n个元素的置换需要计算n-1个元素的置换(递归调用),然后处理n次(插入)。n-1也是如此,以此类推,直到0,这需要恒定的时间(1)。因此O是n*n-1*n-2。。。1或n!。