当前位置:网站首页>《c语言》青蛙跳台阶递归问题
《c语言》青蛙跳台阶递归问题
2022-07-31 06:42:00 【郭郭学习之旅】
题目:
一只青蛙可以一次跳 1 级台阶或一次跳 2 级台阶,例如:跳上第一级台阶只有一种跳法:直接跳 1 级即可。跳上两级台阶,有两种跳法: 每次跳 1 级,跳两次; 或者一次跳 2 级.问要跳上第 n 级台阶有多少种跳法?
思路分析:
首先我们可以考虑到,青蛙在只有一层台阶的时候只会有一种跳法,在两层台阶的时候会有两种跳法

那么我们尝试考虑一下如果有三个台阶呢,小青蛙可以有了多种选择,他可以选择一个一个

也可以选择第一次跳一个台阶,第二次直接跳两个台阶

还可以选择第一次跳两个台阶,然后再跳一个台阶

那么综上所述,我们可以得到
如果有一个台阶的话,小青蛙有一种跳法;
如果有两个台阶的话,小青蛙有两种跳法;
如果有三个台阶的话,小青蛙有三种跳法;
如果有四个台阶的话,小青蛙有五种跳法;
……………………
那么我们可以考虑到,无非小青蛙的跳法就是n-1个台阶的跳法次数+n-2个台阶的跳法次数
所以我们代码可以如下所示
int frog(int n) {
if (n == 1)return 1;
else if (n == 2)return 2;
else return frog(n - 1) + frog(n - 2);
}
好了本次思路就分享到这~~感谢大家三连支持
边栏推荐
- ‘vite‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件。
- 【Go语言入门】一文搞懂Go语言的最新依赖管理:go mod的使用
- 电脑开机密码怎么设置?如何给你的电脑加上“安全锁”
- 手把手教你开发微信小程序自定义底部导航栏
- 任务及任务切换
- Postgresql source code learning (33) - transaction log ⑨ - see the overall process of log writing from the insert record
- 2022.07.29_Daily Question
- ros little turtle drawing
- Embedded system driver primary [2] - _ parameters and dependencies under the kernel module
- Kubernetes scheduling
猜你喜欢

单点登录 思维导图

Linked list implementation and task scheduling

Zabbix6.2惊喜发布!特别优化中大型环境部署的性能!

Financial leasing business

客户端navicat安装教程

Titanic 预测问题

2. (1) Chained storage of stack, operation of chain stack (illustration, comment, code)

超级详细的mysql数据库安装指南

Super detailed mysql database installation guide

MySQL installation to the last step in the write the configuration file failed?And after the installation steps
随机推荐
Leetcode952. 按公因数计算最大组件大小
单点登录 思维导图
科普 | “大姨太”ETH 和 “小姨太”ETC的爱恨情仇
CNN--各层的介绍
DirectExchange switch simple introduction demo
电压源的电路分析知识分享
完美指南|如何使用 ODBC 进行无代理 Oracle 数据库监控?
sort函数(快速排列)的使用方法
进程和线程的区别&&run和start区别与联系
Core Tower Electronics won the championship in the Wuhu Division of the 11th China Innovation and Entrepreneurship Competition
LeetCode:952. 按公因数计算最大组件大小【欧拉筛 + 并查集】
Environment_Variable_and_SetUID
2022.07.24_Daily Question
Automatic translation software - batch batch automatic translation software recommendation
【Go报错】go go.mod file not found in current directory or any parent directory 错误解决
03-SDRAM: Write operation (burst)
2022.07.18_每日一题
Navicat new database
【 TA - frost Wolf _may - "one hundred plan" 】 art 2.3 hard surface
2022.07.20_Daily Question