当前位置:网站首页>青蛙跳台阶
青蛙跳台阶
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;
}
如果觉得写得不错,关注点一点,下期更精彩。
边栏推荐
- Arduino Basic Syntax
- NFT工具合集
- uni-app项目总结
- JSP out.write()方法具有什么功能呢?
- These 4 computer notepad software, you have to try
- IO stream basics
- els 方块变形判断。
- Constructor, this keyword, method overloading, local variables and member variables
- MYSQL(基本篇)——一篇文章带你走进MYSQL的奇妙世界
- GIF making - very simple one-click animation tool
猜你喜欢
Don't know about SynchronousQueue?So ArrayBlockingQueue and LinkedBlockingQueue don't and don't know?
BGP first experiment
玩转NFT夏季:这份工具宝典值得收藏
短视频SEO搜索运营获客系统功能介绍
PHP to read data from TXT file
Double queue implementation stack?Dual stack implementation queue?
NFT工具合集
一文概览最实用的 DeFi 工具
146. LRU 缓存
Arduino Basic Syntax
随机推荐
Cyber-Physical System State Estimation and Sensor Attack Detection
实现删除-一个字符串中的指定字母,如:字符串“abcd”,删除其中的”a”字母,剩余”bcd”,也可以传递多个需要删除的字符,传递”ab”也可以做到删除”ab”,剩余”cd”。
Disk and file system management
Angr(十二)——官方文档(Part3)
146. LRU 缓存
How to find new potential projects?Tools recommended
These 4 computer notepad software, you have to try
CRS management and maintenance
swing的Jlist列表滚动条以及增加元素的问题
Interview high-frequency test questions solution - stack push and pop sequence, effective parentheses, reverse Polish expression evaluation
Kunpeng compile and debug plug-in actual combat
bgp 聚合 反射器 联邦实验
JSP page指令errorPage属性起什么作用呢?
C language character and string function summary (2)
Using the "stack" fast computing -- reverse polish expression
Kotlin协程:创建、启动、挂起、恢复
els block deformation judgment.
How does JSP use request to get the real IP of the current visitor?
els 长条变形
Redis - message publish and subscribe