当前位置:网站首页>青蛙跳台阶(递归和非递归)-------小乐乐走台阶
青蛙跳台阶(递归和非递归)-------小乐乐走台阶
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;
}
边栏推荐
- coming!Dongfang Selection brings goods to the live broadcast of Longjiang agricultural products
- The use of @ symbol in MySql
- MindSpore:【语音识别】DFCNN网络训练loss不收敛
- 【Prometheus】Prometheus联邦的一次优化记录[续]
- Start background services across processes
- Range.CopyFromRecordset method (Excel)
- 又一家公司面试的内容
- Witness the magical awakening of the mini world in HUAWEI CLOUD
- LeetCode 0952. Calculate Maximum Component Size by Common Factor: Mapping / Union Search
- 第十七届“振兴杯”全国青年 职业技能大赛——计算机程序设计员(云计算平台与运维)参赛回顾与总结
猜你喜欢

redis

VBA 连接Access数据库和Excle

经济新闻:错误# 15:初始化libiomp5md。dll,但发现libiomp5md。已经初始化dll。解决方法

开心的聚餐

牛客刷题系列之进阶版(组队竞赛,排序子序列,倒置字符串, 删除公共字符,修理牧场)

NXP IMX8QXP replacement DDR model operation process

MindSpore:【MindSpore1.1】Mindspore安装后验证出现cudaSetDevice failed错误

VBA runtime error '-2147217900 (80040e14): Automation error

The technology is very powerful, do you still need to "manage up"?

部分分类网络性能对比
随机推荐
MindSpore:mindspore有没有类似tf.GradientTape()用来求解梯度的?
【MindSpore1.2.0-rc1产品】num_workers问题
开心的聚餐
C# wpf borderless window add shadow effect
HCIP --- 企业网的三层架构
LeetCode每日一题(1717. Maximum Score From Removing Substrings)
MindSpore:对image作normalize的目的是什么?
高并发秒杀项目总结
ImportError:attempted relative import with no known parent package
nlohmann json 使用指南【visual studio 2022】
第一次进入小程序判断
NXP IMX8QXP更换DDR型号操作流程
卫星电话是直接与卫星通信还是通过地面站?
golang日志库zerolog使用记录
Alibaba Cloud Martial Arts Headline Event Sharing
基于inquirer封装一个控制台文件选择器
VBA runtime error '-2147217900 (80040e14): Automation error
自己需要努力
[PyTorchVideo Tutorial 01] Quickly implement video action recognition
VS Code connects to SQL Server