当前位置:网站首页>青蛙跳台阶(递归和非递归)-------小乐乐走台阶
青蛙跳台阶(递归和非递归)-------小乐乐走台阶
2022-07-30 19:29:00 【果辰辰果】
小青蛙跳台阶
一、 问题描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法???

二、分析问题
当n=1时,有一种跳法
当n=2时,有两种跳法
1.跳一级,跳一级
2.跳两级
当n=3时,有三种跳法
1.跳一级,跳一级,跳一级
2.跳一级,跳两级
3.跳两级,跳一级
先假设f(n)为 n 级台阶的总跳法数;
那么第一次如果选择跳一级的话,剩下的 n-1 级台阶的跳法数就为f(n−1)。
如果第一次跳两级的话,剩下的 n-2 级台阶的跳法就是f(n−2);
所以,当有n个台阶时有f(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;//倒数第一个跳法
int final2 = 2;//倒数第二个跳法
int sum = 0;//计算一共多少种
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;
}
边栏推荐
- Tensorflow2.0 混淆矩阵与打印准确率不符
- 第一次进入小程序判断
- Delay queue optimization (2)
- SimpleOSS第三方库libcurl与引擎libcurl错误解决方法
- coming!Dongfang Selection brings goods to the live broadcast of Longjiang agricultural products
- After watching "Second Uncle", I was even more internalized
- Zabbix 5.0 Monitoring Tutorial (1)
- LeetCode 0952.按公因数计算最大组件大小:建图 / 并查集
- [PyTorchVideo Tutorial 01] Quickly implement video action recognition
- MYSQL(基本篇)——一篇文章带你走进MYSQL的奇妙世界
猜你喜欢

Zabbix 5.0 Monitoring Tutorial (1)

MySQL分库分表

VBA connects Access database and Excel

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

MindSpore:【JupyterLab】查看数据时报错

MongoDB打破了原则引入SQL?

NXP IMX8QXP replacement DDR model operation process

OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.解决方法

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

VBA批量将Excel数据导入Access数据库
随机推荐
几个GTest、GMock的例子
vxe-table实现复选框鼠标拖动选中
HCIP --- 企业网的三层架构
MySQL分库分表
OMP: Error #15: Initializing libiomp5md.dll, but found libiomp5md.dll already initialized.解决方法
DM8:单库单实例搭建本地数据守护服务
Entering the applet for the first time
防抖和节流有什么区别,分别用于什么场景?
SimpleOSS third-party library libcurl and engine libcurl error solution
Swiper轮播图片并播放背景音乐
LeetCode每日一题(1717. Maximum Score From Removing Substrings)
【PHPWord】Quick Start of PHPWord in PHPOffice Suite
架构师如何成长
crontab中写go run不执行的问题
牛客网——华为题库(100~108)
- daily a LeetCode 】 【 191. A number of 1
Zabbix 5.0 Monitoring Tutorial (1)
JsonUtil基于字符串操作josn
Win11如何更改默认下载路径?Win11更改默认下载路径的方法
After 23 years of operation, the former "China's largest e-commerce website" has turned yellow...