当前位置:网站首页>青蛙跳台阶(递归和非递归)-------小乐乐走台阶
青蛙跳台阶(递归和非递归)-------小乐乐走台阶
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;
}
边栏推荐
- MindSpore: CV.Rescale(rescale,shift)中参数rescale和shift的含义?
- Tensorflow2.0 混淆矩阵与打印准确率不符
- MySQl数据库————DQL数据查询语言
- VBA connects Access database and Excel
- Spark学习:编译Spark项目时遇到的报错
- VS Code 连接SQL Server
- 【MindSpore】用coco2017训练Model_zoo上的 yolov4,迭代了两千多batch_size之后报错,大佬们帮忙看看。
- 【网站放大镜效果】两种方式实现
- 6 yuan per catty, why do Japanese companies come to China to collect cigarette butts?
- nlohmann json 使用指南【visual studio 2022】
猜你喜欢

VS Code connects to SQL Server

数据库索引:索引并不是万能药

延时队列优化 (2)

M3SDA:用于多源域自适应的矩匹配

第十七届“振兴杯”全国青年 职业技能大赛——计算机程序设计员(云计算平台与运维)参赛回顾与总结

MindSpore:对image作normalize的目的是什么?
![[PyTorchVideo Tutorial 01] Quickly implement video action recognition](/img/1a/696c5722bb94fabd688a8714ae2e8c.png)
[PyTorchVideo Tutorial 01] Quickly implement video action recognition

Swiper轮播图片并播放背景音乐

Download Win11 how to change the default path?Download Win11 change the default path method

MySql中@符号的使用
随机推荐
自己需要努力
MindSpore:ImageFolderDataset数据读取问题
防抖和节流有什么区别,分别用于什么场景?
刷题记录----字符串
HCIP --- 企业网的三层架构
SimpleOSS third-party library libcurl and engine libcurl error solution
musicApp 的.eslintrc.js
牛客网——华为题库(100~108)
After 23 years of operation, the former "China's largest e-commerce website" has turned yellow...
The technology is very powerful, do you still need to "manage up"?
牛客刷题系列之进阶版(组队竞赛,排序子序列,倒置字符串, 删除公共字符,修理牧场)
MindSpore:【resnet_thor模型】尝试运行resnet_thor时报Could not convert to
The advanced version of the cattle brushing series (search for rotating sorted arrays, inversion of the specified range in the linked list)
LeetCode 0952. Calculate Maximum Component Size by Common Factor: Mapping / Union Search
7.30模拟赛总结
Range.CopyFromRecordset 方法 (Excel)
Niuke.com - Huawei Question Bank (100~108)
来了!东方甄选为龙江农产品直播带货
MYSQL(基本篇)——一篇文章带你走进MYSQL的奇妙世界
启动前台Activity