当前位置:网站首页>青蛙跳台阶
青蛙跳台阶
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;
}
如果觉得写得不错,关注点一点,下期更精彩。
边栏推荐
猜你喜欢

Using the "stack" fast computing -- reverse polish expression

Double queue implementation stack?Dual stack implementation queue?
![[HCIP] BGP Small Experiment (Federation, Optimization)](/img/a2/0967200c69cff3b683dc0af6f314c8.png)
[HCIP] BGP Small Experiment (Federation, Optimization)

路由策略

这 4 款电脑记事本软件,得试试

Business test how to avoid missing?

What is Low-Code?What scenarios is low code suitable for?
![[Headline] Written test questions - minimum stack](/img/67/08f2be8afc780e3848371a1b5e04db.png)
[Headline] Written test questions - minimum stack

NodeJs, all kinds of path

Play NFT summer: this collection of tools is worth collecting
随机推荐
IO流基础
els 长条变形
Grid false data injection attacks detection based on coding strategy
MySQL常用语句整理
els strip deformation
Task execution control in Ansible
ROS dynamic parameters
Identify memory functions memset, memcmp, memmove, and memcpy
Transient Stability Distributed Control of Power System with External Energy Storage
鲲鹏编译调试插件实战
ICML 2022 || 局部增强图神经网络GNN,在 GCN 和 GAT基础上 平均提高了 3.4% 和 1.6%
What is the function of the JSP Taglib directive?
如何发现新的潜力项目?工具推荐
实现删除-一个字符串中的指定字母,如:字符串“abcd”,删除其中的”a”字母,剩余”bcd”,也可以传递多个需要删除的字符,传递”ab”也可以做到删除”ab”,剩余”cd”。
JSP如何使用request获取当前访问者的真实IP呢?
Collection of NFT tools
After an incomplete recovery, the control file has been created or restored, the database must be opened with RESETLOGS, interpreting RESETLOGS.
After reshipment tencent greetings to monitor if the corresponding service does not exist by sc. Exe command to add services
An Enhanced Model for Attack Detection of Industrial Cyber-Physical Systems
[Solution] Emqx startup under win10 reports Unable to load emulator DLL, node.db_role = EMQX_NODE__DB_ROLE = core