当前位置:网站首页>C语言——青蛙跳台阶(递归)
C语言——青蛙跳台阶(递归)
2022-08-04 19:53:00 【硌手的小虫子@】
目录
一、题目描述:
二、解题思路:
三、代码:
一、题目描述:
一只青蛙可以一次跳 1 级台阶或一次跳 2 级台阶,例如:跳上第一级台阶只有一种跳法,直接跳 1 级即可。跳上两级台阶,有两种跳法: 每次跳 1 级,跳两次; 或者一次跳 2 级。问要跳上第 n 级台阶有多少种跳法?
二、解题思路:
通过分析可以发现青蛙跳台阶问题可以类似于一个斐波那契数:当青蛙要跳到第一个台阶时可以跳一个台阶;当青蛙要跳到第二个台阶时可以跳一个2级台阶或者两个1级台阶;当台阶数大于2即N个台阶时,可以从第N-1个台阶跳、也可以从第N-2个台阶跳——walk(n)=walk(n-1)+walk(n-2)。
三、代码:
#include<stdio.h>
int test(int n)
{
if (n <= 2)
return n;
else
return test(n - 1) + test(n - 2);
}
int main()
{
printf("输入要跳的台阶数!!!\n");
int n = 0;
scanf("%d", &n);
int ret = test(n);
printf("有%d种跳法\n", ret);
return 0;
}
边栏推荐
猜你喜欢
随机推荐
刷题-洛谷-P1307 数字反转
微信小程序云开发 | 赠、删、改城市名称信息的应用实现
really time ntp service start command
awk 统计差值记录
图片延迟加载、预加载
If it is test axi dma catch a few words here
哈佛架构 VS 冯·诺依曼架构
「 WAIC 2022 · 黑客马拉松」蚂蚁财富两大赛题邀你来战!
【ASP.NET Core】 中间件
A complete cross-compilation environment records the shell scripts generated by peta
Notepad++更改显示背景
2022年国内手机满意度榜单:华为稳坐国产品牌第一
程序员如何在职场上少走弯路?
性能测试流程
Zip4j使用
Elastic Search 根据匹配分和热度分排序
Chrome 开发者工具 performance 标签页的用法
Storage resource activation system to help new infrastructure
How to manually download and install SAP Fiori tools - Extension Pack for Visual Studio Code
Openharmony first experience (1)