题目:
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法(先后次序不同算不同的结果)。
数据范围:1≤n≤40
要求:时间复杂度:O(n) ,空间复杂度: O(1)
示例:
输入:2
返回值:2
说明:青蛙要跳上两级台阶有两种跳法,分别是:先跳一级,再跳一级或者直接跳两级。因此答案为2
输入:7
返回值:21
只有题解3通过力扣爬楼梯时间要求
题解1:
递归思想,青蛙最后跳的不是一级就是二级。
public class Solution {
public int jumpFloor(int target) {
if(target < 3){
return target;
}else{
return jumpFloor(target-1)+jumpFloor(target-2);
}
}
}
题解2:方案1时间复杂度达到了O(n^2),我们可以创建一个HashMap来减少重复计算,加快计算速度。
class Solution {
public int climbStairs(int n) {
Map<Integer,Integer> hashMap = new HashMap<>();
if(n == 1) return 1;
if(n == 2) return 2;
if(null != hashMap.get(n)){
return hashMap.get(n);
}else {
int result = climbStairs(n-1)+climbStairs(n-2);
hashMap.put(n,result);
return result;
}
}
}
题解3:一般来讲,一个可以用递归来解决的问题都可以转化为用循环迭代来解决
class Solution {
public int climbStairs(int n) {
if(n == 1) return 1;
if(n == 2) return 2;
int result = 0;
int a = 1;
int b = 2;
for(int i=3;i<=n;i++){
result = a + b;
a = b;
b = result;
}
return result;
}
}
同理可解决:
剑指offer10 斐波那契数列
力扣70 爬楼梯