题目:一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
数据范围:1≤n≤40
要求:时间复杂度:O(n) ,空间复杂度:O(1)
示例1
输入:2
返回值:2
说明:青蛙要跳上两级台阶有两种跳法,分别是:先跳一级,再跳一级或者直接跳两级。因此答案为2
示例2
输入:7
返回值:21
方法一:递归
public class Solution {
public int jumpFloor(int target) {
if(target <= 0)
return 0;
if(target == 1)
return 1;
if(target == 2)
return 2;
return jumpFloor(target - 1) + jumpFloor(target - 2);
}
}
方法二:动态规划
public class Solution {
public int jumpFloor(int target) {
int[] memo = new int[2];
memo[0] = 1; //有一节台阶的跳法
memo[1] = 2; //有两阶台阶的跳法
if(target == 1)
return 1;
if(target == 2)
return 2;
int res = 0;
for(int i = 2; i < target; i++) {
res = memo[0] + memo[1];
memo[0] = memo[1];
memo[1] = res;
}
return res;
}
}