题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法(先后次序不同算不同的结果)
思路
方法一:简单的动态规划
(1)状态定义:f(n):跳到第 n 级台阶的总跳发
(2)状态递推:f(n) = f(n-1)+f(n-2)
(3)初始状态:f(0) = 1(第0级台阶即为起点,到达该处只有一种方法,既保持不动);f(1) = 1;
方法二:斐波那契数列
跳台阶问题,同样可以转化为斐波那契数列问题,可以采用求斐波那契数的方法求解
代码
package day3;
public class JumpFloor {
//动态规划
public int jump(int n){
int[] step = new int[n+1];
step[0] = 1;
step[1] = 1;
for(int i = 2;i<=n;i++){
step[i] = step[i-1]+step[i-2];
}
return step[n];
}
//方法二:斐波那契数列
private static int jump2(int n) {
if(n == 0||n == 1){
return 1;
}
if (n == 2) {
return 2;
}
int first = 1;
int second = 2;
int third = 1;
while(n>2){
third = first+second;
first = second;
second = third;
n--;
}
return third;
}
}