当前位置:网站首页>青蛙跳台阶
青蛙跳台阶
2022-08-02 00:14:00 【GD_small_bit】
今天,我将为大家带来青蛙跳台阶的程序,分别以递归和非递归进行实现,话不多说,直接开始主题。
青蛙跳台阶游戏讲解
问题描述:在青蛙的面前有N个台阶,而且青蛙每次都只能跳1~2级的台阶,那么请问,青蛙有多少种方法可以跳上N级的台阶。
假设我们的台阶最开始有1级,那么毫无疑问,青蛙只能以一种方法跳上台阶。
假设我们有二级台阶,那么青蛙便可以有两种方法来到我们的台阶顶部。第一种,青蛙一级一级跳到顶部;第二种,青蛙直接跳两级来到顶部。
假设我们有三级台阶,那么青蛙就有三种方法跳到台阶顶部。第一种,选择一级一级跳到顶部;第二种,选择先跳两级台阶,再跳一级台阶来到顶部;第三种,选择先跳一级台阶,再跳两级台阶来到顶部。
假设我们有四级台阶,那么青蛙就有五种方法来到顶部。第一种,一级一级跳到顶部;第二种,先跳两次一级,再跳一次两级;第三种,先跳一次二级,再跳两次一级;第四种,先跳一级,再跳两级,再跳一级;第五种,直接跳两次两级。
当N为1时,方法为1;
当N为2时,方法为2;
当N为3时,方法为3;
当N为4时,方法为5;
…
…
…
观察可以得知,当有N级台阶时,方法为有N-1的台阶和N-2的台阶方法之和。
递归实现青蛙跳台阶
#include<stdio.h>
int frog (int n)
{
if(n==1)
{
return 1;
}
else if(n==2)
{
return 2;
}
else
{
return frog(n-1)+frog(n-2);
}
}
int main ()
{
int N = 0;
int ret = 0;
scanf("%d",&N);
ret = frog(N);
printf("%d",ret);
return 0;
}
非递归实现青蛙跳台阶
```c
#include<stdio.h>
int frog (int n)
{
int a = 1;
int b = 2;
int c = 0;
if(n==1)
{
return a;
}
else if(n==2)
{
return b;
}
else
{
while(n>=3)
{
c = a + b;
a = b;
b = c;
n--;
}
return c;
}
}
int main ()
{
int N = 0;
int ret = 0;
scanf("%d",&N);
ret = frog(N);
printf("%d",ret);
return 0;
}
如果觉得写得不错,关注点一点,下期更精彩。
边栏推荐
- els block deformation judgment.
- MLX90640 红外热成像仪测温传感器模块开发笔记(十) 成果展示-红眼睛相机
- Difference between JSP out.print() and out.write() methods
- uni-app project summary
- JSP built-in object out object function introduction
- Detailed explanation of JSP request object function
- Async/await principle and execution sequence analysis
- Business test how to avoid missing?
- JSP request对象功能详解说明
- Using the "stack" fast computing -- reverse polish expression
猜你喜欢
What is Low-Code?What scenarios is low code suitable for?
How to find new potential projects?Tools recommended
Double queue implementation stack?Dual stack implementation queue?
当奈飞的NFT忘记了Web2的业务安全
Don't concatenate strings with jOOQ
An interesting project--Folder comparison tool (1)
攻防世界-web-Training-WWW-Robots
146. LRU 缓存
回顾历史5次经济衰退时期:这一次可能会有何不同?
Microsoft PC Manager V2.1 beta version officially released
随机推荐
ICML 2022 || 局部增强图神经网络GNN,在 GCN 和 GAT基础上 平均提高了 3.4% 和 1.6%
BGP 第一次实验
字符串分割函数strtok练习
业务测试如何避免漏测 ?
TCL: Pin Constraints Using the tcl Scripting Language in Quartus
Constructor, this keyword, method overloading, local variables and member variables
Redis - message publish and subscribe
JSP 如何获取request对象中的路径信息呢?
磁盘与文件系统管理
JSP Taglib指令具有什么功能呢?
Transient Stability Distributed Control of Power System with External Energy Storage
An overview of the most useful DeFi tools
[Solution] Emqx startup under win10 reports Unable to load emulator DLL, node.db_role = EMQX_NODE__DB_ROLE = core
测试点等同于测试用例吗
IP Core: FIFO
链上治理为何如此重要,波卡Gov 2.0又会如何引领链上治理的发展?
Routing strategy
poker question
Are test points the same as test cases?
Web开发