描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
示例1
输入:
2
返回值:
2
示例2
输入:
7
返回值:
21
题目分析
翻译一下题目就是:
数组中元素总和是n, 数组各个元素可以是1或者是2,不限数组大小长度,任意排列组合,共有多少种排法?
啊这。。。好像分析了个寂寞,看不出啥。。。
那换种思考方法,一个一个看一下:
1级台阶有1种方法,f(1) = 1
2级台阶有2种方法,f(2) = 2
3级台阶有3种方法,f(3) = 3
4级台阶有5种方法,f(4) = 5
。。。。
那么 f(n) = f(n-1) + f(n-2)
这不是斐波那契数列同学吗?哈哈,昨天刚写了这个数列https://blog.csdn.net/bihao8481/article/details/119274583?spm=1001.2014.3001.5501
今天再来一遍,还是用两种方法来解。
法一:递归方法
public class Solution {
public int jumpFloor(int target) {
if(target==1){
return 1;
}
if(target==2){
return 2;
}else{
return jumpFloor(target-1)+jumpFloor(target-2);
}
}
}
法二:迭代方法
public class Solution {
public int jumpFloor(int target) {
int first = 1;
int second = 2;
int third = 3;
if(target == 1){
return 1;
}
if(target == 2){
return 2;
}else{
for(int i = 3; i<= target; i++){
third = first + second;
first = second;
second = third;
}
}
return third;
}
}
越来越熟练了呢~