当前位置:网站首页>Frog jumping steps (recursive and non-recursive) ------- Xiaolele walks the steps
Frog jumping steps (recursive and non-recursive) ------- Xiaolele walks the steps
2022-07-30 19:36:00 【Fruit Chenchen】
小青蛙跳台阶
一、 问题描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级.求该青蛙跳上一个n级的台阶总共有多少种跳法???
二、分析问题
当n=1时,有一种跳法
当n=2时,有两种跳法
1.跳一级,跳一级
2.跳两级
当n=3时,There are three jumps
1.跳一级,跳一级,跳一级
2.跳一级,跳两级
3.跳两级,跳一级
先假设f(n)为 n 级台阶的总跳法数;
Then if you choose to skip one level for the first time,剩下的 n-1 The number of jumps for each step is f(n−1).
If you jump two levels for the first time,剩下的 n-2 级台阶的跳法就是f(n−2);
所以,当有nThere are stepsf(n)=f(n-1)+f(n-2)种跳法.
三、代码实现(递归)
#include<stdio.h>
int steps(int x)
{
if (x == 1)
{
return 1;
}
if (x == 2)
{
return 2;
}
return steps(x - 1) + steps(x - 2);
}
int main()
{
int n = 0;
scanf("%d", &n);
printf("%d", steps(n));
return 0;
}
四、代码实现(非递归)
#include<stdio.h>
int steps(int x)
{
if (x < 3)
{
return x;
}
int final1 = 1;//Countdown to the first jump
int final2 = 2;//The penultimate jump
int sum = 0;//Count how many in total
for (int i = 3; i <= x; i++)
{
sum = final1 + final2;
final1 = final2;
final2 = sum;
}
return sum;
}
int main()
{
int n = 0;
scanf("%d", &n);
printf("%d", steps(n));
return 0;
}
边栏推荐
- 尊重客观事实
- mysql慢查询优化
- 【MindSpore】用coco2017训练Model_zoo上的 yolov4,迭代了两千多batch_size之后报错,大佬们帮忙看看。
- MySQL分组后取最大一条数据【最优解】
- 第一次进入小程序判断
- MindSpore: CV.Rescale(rescale,shift)中参数rescale和shift的含义?
- Zabbix 5.0 监控教程(一)
- 【flink】报错整理 Could not instantiate the executor. Make sure a planner module is on the classpath
- Trial writing C language sanbang
- MindSpore:自定义dataset的tensor问题
猜你喜欢
2种手绘风格效果比较,你更喜欢哪一种呢?
VBA runtime error '-2147217900 (80040e14): Automation error
Linux下安装Mysql5.7,超详细完整教程,以及云mysql连接
MySQL分组后取最大一条数据【最优解】
nlohmann json 使用指南【visual studio 2022】
MindSpore:【Resolve node failed】解析节点失败的问题
【hbuilder】运行不了部分项目 , 打开终端 无法输入指令
Google's AlphaFold claims to have predicted almost every protein structure on Earth
LeetCode 0952. Calculate Maximum Component Size by Common Factor: Mapping / Union Search
生物医学论文有何价值 论文中译英怎样翻译效果好
随机推荐
Tensorflow2.0 confusion matrix does not match printing accuracy
redis
还有三天忙完
JS提升:Promise中reject与then之间的关系
NXP IMX8QXP更换DDR型号操作流程
MySQl数据库————DQL数据查询语言
nlohmann json 使用指南【visual studio 2022】
[Prometheus] An optimization record of the Prometheus federation [continued]
MindSpore:自定义dataset的tensor问题
VBA connects Access database and Excel
【MindSpore1.2.0-rc1产品】num_workers问题
golang日志库zerolog使用记录
The Meta metaverse division lost 2.8 billion in the second quarter!Still want to keep betting?Metaverse development has yet to see a way out!
【网站放大镜效果】两种方式实现
MindSpore:【JupyterLab】查看数据时报错
Range.CopyFromRecordset 方法 (Excel)
跨进程启动后台服务
2种手绘风格效果比较,你更喜欢哪一种呢?
MindSpore: CV.Rescale(rescale,shift)中参数rescale和shift的含义?
MySQL数据库————视图和索引