当前位置:网站首页>青蛙跳台阶
青蛙跳台阶
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;
}
如果觉得写得不错,关注点一点,下期更精彩。
边栏推荐
- Constructor, this keyword, method overloading, local variables and member variables
- poker question
- 2022/08/01 Study Notes (day21) Generics and Enums
- 众筹DAO“枯萎”的缩影:曾拍下《沙丘》未出版手稿的Spice DAO解散
- 以交易为生是一种什么体验?
- An interesting project--Folder comparison tool (1)
- JSP built-in object out object function introduction
- 一文概览最实用的 DeFi 工具
- Trie详解
- 辨析内存函数memset、memcmp、memmove以及memcpy
猜你喜欢

Kunpeng compile and debug plug-in actual combat

Short video seo search optimization main content

c语言字符和字符串函数总结(二)

Arduino Basic Syntax

Automatic conversion of Oracle-style implicit joins to ANSI JOINs using jOOQ

Pytorch seq2seq 模型架构实现英译法任务

Play NFT summer: this collection of tools is worth collecting

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

Short video SEO search operation customer acquisition system function introduction
![[Headline] Written test questions - minimum stack](/img/67/08f2be8afc780e3848371a1b5e04db.png)
[Headline] Written test questions - minimum stack
随机推荐
How to design a circular queue?Come and learn~
Active Disturbance Rejection Control of Substation Inspection Robot Based on Data Drive
Collection of NFT tools
Looking back at 5 recessionary times in history: How might this time be different?
Cyber-Physical System State Estimation and Sensor Attack Detection
MLX90640 红外热成像仪测温模块开发笔记(完整版)
After reshipment tencent greetings to monitor if the corresponding service does not exist by sc. Exe command to add services
When Netflix's NFTs Forget Web2 Business Security
JSP Taglib指令具有什么功能呢?
思维导图,UML在线画图工具
测试点等同于测试用例吗
回顾历史5次经济衰退时期:这一次可能会有何不同?
06-SDRAM : SDRAM control module
Angr(十二)——官方文档(Part3)
poker question
An Enhanced Model for Attack Detection of Industrial Cyber-Physical Systems
使用jOOQ将Oracle风格的隐式连接自动转换为ANSI JOIN
Unknown CMake command “add_action_files“
Async/await principle and execution sequence analysis
NFT工具合集