当前位置:网站首页>青蛙跳台阶(递归和非递归)-------小乐乐走台阶
青蛙跳台阶(递归和非递归)-------小乐乐走台阶
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;
}
边栏推荐
猜你喜欢

What is the difference between a cloud database and an on-premises database?

【网站放大镜效果】两种方式实现

Golang logging library zerolog use record

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

VBA batch import Excel data into Access database

MySQL分库分表

The advanced version of the cattle brushing series (search for rotating sorted arrays, inversion of the specified range in the linked list)

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

Encapsulates a console file selector based on inquirer

VBA 运行时错误‘-2147217900(80040e14):自动化(Automation)错误
随机推荐
经济新闻:错误# 15:初始化libiomp5md。dll,但发现libiomp5md。已经初始化dll。解决方法
阿里云武林头条活动分享
coming!Dongfang Selection brings goods to the live broadcast of Longjiang agricultural products
Day31 LeetCode
What is a RESTful API?
数据库索引:索引并不是万能药
MindSpore:Cifar10Dataset‘s num_workers=8, this value is not within the required range of [1, cpu_thr
又一家公司面试的内容
NXP IMX8QXP更换DDR型号操作流程
requet.getHeader("token") is null
【flink】报错整理 Could not instantiate the executor. Make sure a planner module is on the classpath
VS Code connects to SQL Server
跨域问题的解决方法
The advanced version of the Niu Ke brushing series (team competition, sorting subsequences, inverting strings, deleting common characters, repairing pastures)
MindSpore:【JupyterLab】按照新手教程训练时报错
自己需要努力
开心的聚餐
【PHPWord】Quick Start of PHPWord in PHPOffice Suite
MySQL database - DQL data query language
Common linked list problems and their Go implementation