C++用递归实现求解相关函数
//递归实现Hanoi塔问题
#include<iostream>
#include<cstdlib>
using namespace std;
#define MAXSIZE 100
#define OK 1
#define ERROR 0
typedef int Status;
typedef int Elemtype;
Status move(int n, char A, char C)//进行移东,将A移动到C柱子上
{
int m = 0;
cout << ++m << "," << n << "," << A << "," << C;
return OK;
}
Status Hanoi(int n, char A, char B, char C)//A为起始柱子,B为辅助柱子,C为目的柱子
{
if (n == 1)
{
move(1, A, C);
cout << "进行一次移动,从A塔移动到C塔。" << endl;
}
else
{
Hanoi(n - 1, A, C, B);
move(n, A, C);
Hanoi(n - 1, B, A, C);
}
return OK;
}
//递归求阶乘n!
Status Fat(int n)
{
if (n == 1) return 1;
else
{
return n * Fat(n - 1);
}
}
//递归求斐波那契函数
Status Fib(int n)
{
if (n == 1 || n == 2) return 1;
else return Fib(n - 1) + Fib(n + 1);
}