Somethings about Floors题解
2024-09-05 17:52:41
题目内容:一个楼梯有N级(N >=0), 每次走1级或2级, 从底走到顶一共有多少种走法?
输入要求:只有一行输入,并且只有一个数N(如果N > 20,则N = N%21,即保证N的范围控制为:0 <= N <= 20,当取模后的值为0时,输出1),代表这个楼梯的级数。
输出要求:只有一行,输出从底到顶的走法,后面有换行。
参考样例:
输入: 3
输出: 3
Hint:
问题分解。
分析:
这道题目应该用递归的思想去解决推导出公式。如果只有一级楼梯,那么走法只有一种;如果有两级楼梯,那么走法有两种;...如果有N(N > 2)级楼梯,因为一次可以上一级或者两级,那么我们可以考虑从N-1级和N-2级楼梯到N级的走法,那么F(N) = F(N-1) + F(N-2)。
我的代码:
#include <stdio.h>
int main() {
int f0, f1, a;
int b, n, i;
scanf("%d", &n);
n = n % ;
if (n == || n == ) {
printf("%d\n", );
return ;
}
f0 = ;
f1 = ;
for (i = ; i <= n; i++) {
a = f0 + f1;
f0 = f1;
f1 = a;
}
printf("%d\n", f1);
return ;
}
标答:
// from younglee
// solve the problem in two different way, with recursion and no recursion.
#include<stdio.h>
#include<string.h>
#define N 100 #define RECUR 1
#define MODE 0 int dealWithRecursion(int f);
int dealWithNoRecursion(int f);
// to save the result.
int arr[N]; int main(void) {
int floor;
scanf("%d", &floor);
floor %= ;
if (MODE == RECUR) {
printf("%d\n", dealWithRecursion(floor));
} else {
memset(arr, , sizeof(arr));
printf("%d\n", dealWithNoRecursion(floor));
}
return ;
} int dealWithRecursion(int f) {
if (f == || f == ) return ;
return (dealWithRecursion(f - ) + dealWithRecursion(f - ));
} int dealWithNoRecursion(int f) {
if (arr[f] != ) return arr[f];
int result;
if (f == || f == ) result = ;
else result = dealWithNoRecursion(f - ) + dealWithNoRecursion(f - );
arr[f] = result;
return result;
}
这里用了两种方法,递归与非递归。
最新文章
- 查询目前运行状态-CPU等情况
- 让树莓派开机发送自己的ip到邮箱
- Java使用ZXing生成二维码条形码
- JS实现转动效果
- 运用Microsoft.DirectX.DirectSound和Microsoft.DirectX实现简单的录音功能
- sql 两列相加存到另一列
- 启用域中对象的";防止意外删除";功能
- Leetcode: Alien Dictionary &;&; Summary: Topological Sort
- Memcache的部署和使用
- 2017.3.3自测j纠错题.
- COM学习(三)——COM的跨语言
- Oracle实战笔记(第二天)
- hadoop小知识札记
- linux 中的 open() read() write() close() 函数
- 1分钟完美安装最新CentOS+Nginx+PHP-FPM+MySQL
- django之异常错误2(Error was: No module named sqlite3.base)
- Java—关于String的分析
- katalon系列十:Katalon Studio自定义关键字之拖拽
- TVS
- 浅谈Object.create