Fork me on GitHub

【剑指offer】跳台阶

问题一

一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。

解决方案

这是一个典型的斐波那契数问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public:
//递归写法
int jump(int n )
{
if (n <2)
{
return 1;
}

return jump(n - 1) + jump(n - 2);
//非递归写法
int jumpFloor(int number) {
if (number == 1)
{
return 1;
}
int a = 1;
int b = 1;
int c = a+b;

while (number>2)
{
a = b;
b = c;
c = a + b;
number--;
}
return c;
}
};

本文标题:【剑指offer】跳台阶

文章作者:LiuXiaoKun

发布时间:2018年10月02日 - 15:10

最后更新:2019年03月31日 - 21:03

原始链接:https://LiuZiQiao.github.io/2018/10/02/【剑指offer】青蛙跳台阶/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%