提到有关递归的应用,相信很多人首先想到的问题便是fibonacci数列问题,或者是青蛙跳台阶问题。没错,这两个问题都是典型的应用递归求解的问题,但是与之对应的迭代方法却效率较高,且并不难理解。我认为递归调用的最好的应用便是汉诺塔问题。
#include<iostream>
using namespace std;
void move(char start,char end)
{
cout<<start<<">>>>>>>>>>>>>>>>>"<<end<<endl;
}
void hannoi(char first,char middle,char third,int number)
{
if(1==number)
move(first,third);
else
{
hannoi(first,third,middle,number-1);
move(first,third);
hannoi(middle,first,third,number-1);
}
}
int main()
{
cout<<"Input the disk number:";
int num;
cin>>num;
hannoi('A','B','C',num);
return 0;
}