汉诺塔:
#include<iostream>
using namespace std;
int cnt = 0;
void move(int n,char a,char b)
{
cout << ++cnt << " move disk " << n << " from " << a << " to " << b << endl;
}
void hanoi(int n,char a,char b,char c)
{
if (n == 1)
{
move(1, a, c);
}
else
{
hanoi(n - 1, a, c, b);
move(n, a, c);
hanoi(n - 1, b, a, c);
}
}
int main()
{
hanoi(10, 'a', 'b', 'c');
return 0;
}
递归累加:
#include<iostream>
using namespace std;
long long sumto(int n) //返回 0~n的总和
{
if (n == 0)
{
return 0;
}
else
{
return n + sumto(n - 1);
}
}
int main()
{
cout << sumto(5) << endl;
}