代码随想录算法训练营 day38 | 509. 斐波那契数、70. 爬楼梯、746. 使用最小花费爬楼梯


代码随想录

509. 斐波那契数

思路

思路:按照递推公式f(n)=f(n-1)+f(n-2)写代码
遍历即从小到大的数字遍历,因为n=0和n=1是已经有初始化的值的。

代码

class Solution {
    public int fib(int n) {
        if(n == 1|| n==0) return n; 
        int dn=0;
        int dn_1 = 1;
        int dn_2 = 0;

        for(int i =2;i<=n;i++){
            dn = dn_1 + dn_2;
            dn_2 = dn_1;
            dn_1 = dn;
            
        }

        return dn;

    }
}

70. 爬楼梯

思路

定义d[n],表示到达第n阶的时候有d[n]种方法。
递推公式:d[n]=d[n-1]+d[n-2]
初始化:d[1]=1,d[2]=2

代码

class Solution {
    public int climbStairs(int n) {
        if(n==1 || n==2) return n;
        int[] d = new int[n];
        d[0]=1;
        d[1]=2;
        for(int i=2;i<n;i++){
            d[i]=d[i-1]+d[i-2];
        }
        return d[n-1];

    }
}

746. 使用最小花费爬楼梯

思路

思路:
定义d[n] 为达到第n个台阶的最低花费。
递推公式为:d[n] = min(d[n-1]+cost[n-1],d[n-2],cost[i-2])
因为每次到第n阶有两种可能, 即从第n-1or从第n-2阶上俩。
选择最少的那个即可
遍历顺序为从前往后,
初始化:d[0]=0,d[1]=0

代码

class Solution {
    public int minCostClimbingStairs(int[] cost) {
        int len = cost.length;
        int d[] = new int[len+1];
        d[0] = 0;
        d[1] = 0;

        for(int i = 2;i<=len;i++){
            d[i] = Math.min(d[i-1]+cost[i-1],d[i-2]+cost[i-2]);
        }

        return d[len];

    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值