HandsomeDong - 七里翔


  • Home

  • Categories

  • Archives

  • Search

跳台阶

Posted on 2019-06-20 | In 算法题 , 剑指offer算法题

题目描述

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

解题思路

f(n) = f(n-1) + f(n-2)

代码实现

递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int jumpFloor(int number) {
if (number < 1){
return 0;
} else if (number == 1) {
return 1;
} else if (number ==2) {
return 2;
} else {
return jumpFloor(number - 1) + jumpFloor(number - 2);
}
}
};

非递归

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int jumpFloor(int number) {
if (number < 1){
return 0;
}

if ((number == 1) || (number == 2)){
return number;
}

int first = 2, second = 1, sum = 0;

for (int i = 3; i <= number; i++) {
sum = first + second;
second = first;
first = sum;
}
return sum;
}
};
1…151617…24
HandsomeDong

HandsomeDong

24 posts
17 categories
10 tags
  • github
© 2024 HandsomeDong
Powered by Hexo
|
Theme — NexT.Pisces v5.1.4