题目描述
小白正在上楼梯,楼梯有n阶台阶,小白一次可以上1阶,2阶,3阶。
实现一个方法,计算小白有多少种上楼梯的方式。
输入输出
输出:台阶数量。
输出:多少种上楼梯的方式
例如:4阶楼梯 有7种方式(输入4,输出7)
实现思路
有三种上楼梯的方式,1阶,2阶,3阶。
使用递归就是要把问题化成若干子问题,让总的台阶数划分到1阶,2阶,3阶。使子问题的方法相加等于总方法。
代码实现
#include<stdio.h>
int topBar(int step){
if(step==0){//当有0阶台阶的时候,需要返回1种方法。可以理解为被迫调试代码使结果正确
return 1;
}
if(step==1){
return 1;
}
if(step==2){
return 2;
}
return topBar(step-1)+topBar(step-2)+topBar(step-3);
}
int main(){
int step;
scanf("%d",&step);//台阶数
int x=topBar(step);
printf("%d",x);
return 0;
}