Broadview 2020-06-12
其实和八皇后的算法差不多,八皇后不检查斜线的结果就是全排列,此外八皇后中检查皇后位置麻烦,这里只要把列表转成词典,检查一下长度就行了(有重复元素,比如到第二层,应该是1,2,如果是1,1,那么词典长度就只有1了,需要排除):
def permutation(n,floor,per): for pos in range(n): if len(set(per + [pos])) == floor: if floor == n: yield [pos,] else: for result in permutation(n,floor+1, per + [pos,]): yield [pos,] + result for res in permutation(3,1,[]): print(res)
结果:
[0, 1, 2]
[0, 2, 1]
[1, 0, 2]
[1, 2, 0]
[2, 0, 1]
[2, 1, 0]