当前位置:网站首页>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;
}
边栏推荐
猜你喜欢

win2003下FTP服务器如何搭建

redis

浅聊对比学习(Contrastive Learning)第一弹

VS Code 连接SQL Server

MindSpore:【JupyterLab】按照新手教程训练时报错

MySQL六脉神剑,SQL通关大总结

The 17th "Revitalization Cup" National Youth Vocational Skills Competition - Computer Programmers (Cloud Computing Platform and Operation and Maintenance) Participation Review and Summary

防抖和节流有什么区别,分别用于什么场景?

MySQl数据库————DQL数据查询语言

HCIP --- 企业网的三层架构
随机推荐
Spark学习:用spark实现ETL
Talking about Contrastive Learning (Contrastive Learning) the first bullet
MySQl数据库————DQL数据查询语言
055 c# print
阿里面试这些微服务还不会?那还是别去了,基本等通知
青蛙跳台阶(递归和非递归)-------小乐乐走台阶
MySQL分库分表
7.30模拟赛总结
谷歌AlphaFold近日宣称预测出地球上几乎所有蛋白质结构
第十七届“振兴杯”全国青年 职业技能大赛——计算机程序设计员(云计算平台与运维)参赛回顾与总结
生物医学论文有何价值 论文中译英怎样翻译效果好
MindSpore:【语音识别】DFCNN网络训练loss不收敛
MindSpore:npu 多卡训练自定义数据集如何给不同npu传递不同数据
Entering the applet for the first time
MySQL分组后取最大一条数据【最优解】
开心的聚餐
MySQL database - views and indexes
OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.解决方法
Does the satellite phone communicate directly with the satellite or through a ground station?
Go system collection