本文共 944 字,大约阅读时间需要 3 分钟。
递归,即定义一组基本操作,这组操作将规模小一点(或大一点)的操作当做一个整体——无需关心它的细节,只当它已经完成了——然后执行剩下的操作。而在更小或更大的规模中也依此操作,直到规模达到预定值。
当A塔上有n个盘子是,先将A塔上编号1至n-1的盘子(共n-1个)移动到B塔上(借助C塔),然后将A塔上最大的n号盘子移动到C塔上,最后将B塔上的n-1个盘子借助A塔移动到C塔上。
综上所述,除了只有一个盘子时不需要借助其他塔外,其余情况均一样(只是事件的复杂程度不一样)。
pow(2, n) - 1
#include#include //pow(a, b)using namespace std;void move(int n, char x, char y){ cout << n << " from " << x << " to " << y << endl;}void hnt(int n, char from, char to, char depend){ if(n == 1) move(1, from, to); else { hnt(n - 1, from, depend, to); move(n, from, to); hnt(n - 1, depend, to, from); }}int main(){ int n; char a = 'A', b = 'B', c = 'C'; cin >> n; cout << pow(2, n) - 1 << endl; hnt(n, a, c, b); return 0;}