实例:汉诺塔问题
n个圆盘3个柱子abc 一次动一个盘子
把上面n-1个盘看成一个整体,下面1个盘看成一个整体
- n-1盘经过c移动到b
- 第n盘到c
- n-1盘经过a到c
1 3步就是小一规模的汉诺塔
移动次数递推式 h(x)=2h(x-1)+1
def hanoi(n, a, b, c):
if n > 0:
hanoi(n - 1, a, c, b)
print("moving from %s to %s" % (a, c))
hanoi(n - 1, b, a, c)
hanoi(3, 'A', 'B', 'C')
# moving from A to C
# moving from A to B
# moving from C to B
# moving from A to C
# moving from B to A
# moving from B to C
# moving from A to C