一.汉诺塔问题:
1.代码:
#include <stdio.h>
void hanoi(int n,char source,char destination,char transit)
{
if(n <= 0)
return;
else
{
hanoi(n - 1,source,transit,destination);
printf("%c -> %c ",source,destination);
hanoi(n - 1,transit,destination,source);
}
}
int hanoiSum(int n)
{
if(n == 1)
return 1;
else
{
return 2*hanoiSum(n - 1) + 1;
}
}
void hanoiText()
{
printf("3 plates:\r\n");
hanoi(3,'A','B','C');
printf("\n");
printf("移动次数:%d\n",hanoiSum(3));
printf("6 plates:\r\n");
hanoi(6,'A','B','C');
printf("\n");
printf("移动次数:%d\n",hanoiSum(6));
printf("1 plates:\r\n");
hanoi(1,'A','B','C');
printf("\n");
printf("移动次数:%d\n",hanoiSum(1));
}
int main()
{
hanoiText();
}
2.运行结果:
3 plates:
A -> B A -> C B -> C A -> B C -> A C -> B A -> B
移动次数:7
6 plates:
A -> C A -> B C -> B A -> C B -> A B -> C A -> C A -> B C -> B C -> A B -> A C -> B A -> C A -> B C -> B A -> C B -> A B -> C A -> C B -> A C -> B C -> A B -> A B -> C A -> C A -> B C -> B A -> C B -> A B -> C A -> C A -> B C -> B C -> A B -> A C -> B A -> C A -> B C -> B C -> A B -> A B -> C A -> C B -> A C -> B C -> A B -> A C -> B A -> C A -> B C -> B A -> C B -> A B -> C A -> C A -> B C -> B C -> A B -> A C -> B A -> C A -> B C -> B
移动次数:63
1 plates:
A -> B
移动次数:1
二.累加问题(递归)
1.代码:
#include <stdio.h>
int addTo(int n)
{
if(n <= 0)
{
return 0;
}
else
{
return addTo(n - 1) + n;
}
}
void addToText()
{
int n;
n = 6;
printf("0加到%d等于%d\n",n,addTo(n));
n = 1;
printf("0加到%d等于%d\n",n,addTo(n));
n = -1;
printf("0加到%d等于%d\n",n,addTo(n));
}
int main()
{
addToText();
}
2.运行结果:
0加到6等于21
0加到1等于1
0加到-1等于0