一.递归求和
1.总代码
#include<stdio.h>
int addTo(int paraN) {
int tempSum;
printf("entering addTo(%d)\r\n",paraN);
if (paraN <= 0) {
return 0;
}
else{
tempSum = addTo(paraN - 1) + paraN;
printf(" return %d\r\n",tempSum);
return tempSum;
}
}
int clearAddTo(int paraN) {
if (paraN <= 0){
return 0;
}
else{
return clearAddTo(paraN - 1) + paraN;
}
}
void addToTest() {
int n, sum;
printf("---addToTest begins. ----\r\n");
n = 4;
sum = addTo(n);
printf("\r\n 0 adds to %d gets %d.\r\n",n,sum);
n = 1;
sum = addTo(n);
printf("\r\n 0 adds to %d gets %d.\r\n",n,sum);
n = -1;
sum = addTo(n);
printf("\r\n 0 adds to %d gets %d.\r\n",n,sum);
printf("----addToTest ends.\r\n");
}
int main(){
addToTest();
return 0;
}
2.运行结果
----addToTest begins. ----
2 plates
A -> C
A -> B
C -> B
3 plates
A -> B
A -> C
B -> C
A -> B
C -> A
C -> B
A -> B
----addToTest ends.
二.汉诺塔
1.先上图
2.再上代码
#include<stdio.h>
void hanoi(int paraN, char paraSource, char paraDestination, char paraTransit) {
if (paraN <= 0){
return;
}
else{
hanoi(paraN - 1, paraSource, paraTransit, paraDestination);
printf("%c -> %c \r\n",paraSource, paraDestination);
hanoi(paraN - 1, paraTransit, paraDestination, paraSource);
}
}
void hanoiTest(){
printf("----addToTest begins. ---- \r\n");
printf("2 plates \r\n");
hanoi(2,'A','B','C');
printf("3 plates \r\n");
hanoi(3,'A','B','C');
/*printf("5 plates \r\n");
hanoi(5,'1','2','3'); */
printf("----addToTest ends.\r\n");
}
int main(){
hanoiTest();
return 0;
}
3.运行结果
----addToTest begins. ----
2 plates
A -> C
A -> B
C -> B
3 plates
A -> B
A -> C
B -> C
A -> B
C -> A
C -> B
A -> B
----addToTest ends.
总体思想,因为不能将大的盘子放在小的盘子上面,所以最大的那个盘子位置不会影响到上面n-1个盘子的移动,因此我们只需要将上面的盘子都移动到另一个柱子上然后将最后一个盘子移动到目标柱子上然后将前面n-1个盘子以同样的原理移动就可以做到将所有的盘子都移动到目标柱子上面了。