【每日一题】【递归实现、自下而上、优化】-2022年1月12日-NC68 跳台阶

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

数据范围:0 \leq n \leq 400≤n≤40
要求:时间复杂度:O(n)O(n) ,空间复杂度: O(1)O(1)

 

 

方法1:函数递归

public class Solution {
    public int jumpFloor(int target) {
        if(target == 1 || target == 0) {
            return 1;
        }
        return jumpFloor(target - 1) + jumpFloor(target - 2);
    }
}

方法2:自下而上,使用数组

复制代码
public class Solution {
    public int jumpFloor(int target) {
        int[] res = new int[target + 1];
        res[0] = 1;
        res[1] = 1;
        for(int i = 2; i <= target; i++) {
            res[i] = res[i - 1] + res[i - 2];
        }
        return res[target];
    }
}
复制代码

注意:数组名起为res/f都行

方法3:变量空间的优化

复制代码
public class Solution {
    public int jumpFloor(int target) {
        int p = 1, q = 1;
        //和自下而上的方法使用相同的循环结构
        for(int i = 2; i <= target; i++) {
            int temp = p;
            p = p + q;
            q = temp;
        }
        return p;
    }
}
复制代码

注意:可以和自下而上基于数组的方法使用相同的循环结构

posted @   哥们要飞  阅读(30)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
点击右上角即可分享
微信分享提示