recursion - 递归函数计数。河内塔的台阶
问题描述
编写一个递归函数,返回解决 N 个盘的河内塔问题所需的步数。
输入 n=3 输出 7
这是代码-
private static int counttoh(int n,String T1,String T2,String T3)
{int count=0;
if(n==0)
return 1;
count+=counttoh(n-1,T1,T3,T2);
count+=counttoh(n-1,T3,T2,T1);
return count;
}
我的函数 counttoh 给出 4 作为输出,如果我正在做 return count-1 它给出 1 ,任何人都可以帮助我解决这个问题。
解决方案
#include <stdio.h>
int move(int n, char source, char destination, char spare)
{ int count = 1;
if (n==1){
printf("\n\nMove a disc from %c to %c", source, destination);
}
else{
count += move(n-1, source, spare, destination);
move(1, source, destination, spare);
count += move(n-1, spare, destination, source);
}
return count;
}
int main()
{
int n, steps;
char A, B, C;
printf("Enter the number of disc :- ");
scanf("%d", &n);
printf("\nHere A is source, B is destination, C is spare.");
steps = move(n, 'A', 'B', 'C');
printf("\n\nNumber of steps taken is %d", steps);
return 0;
}
推荐阅读
- json - 杰克逊反序列化包含对象数组的对象
- cordova - 无法在 ionic 中获取 Ram 和存储信息
- ios - 为什么这个 IBDesignable 类不在情节提要上显示其更改?
- android - 用于业务集群的 Android 地图
- php - 如何在没有计数器的情况下使用 PHP 上传多个文件?
- excel - VBA - IF 语句不
- java - Apache SSHD:仅允许列入白名单的命令
- jquery - 根据 li 文本过滤,如果匹配则显示 ul
- android - Android RxJava2 改造和 ViewPager
- spring-jms - 柑橘模拟器如何在不同队列中发送和接收java对象