代码随想录二刷 Day41

509. 斐波那契数

这个题简单入门,注意下N小于等于1的情况就可以

cpp 复制代码
class Solution {
public:
    int fib(int n) {
        if (n <= 1) return n;   //这句不写的话test能过但是另外的过不了
        vector<int> result(n + 1); //定义存放dp结果的数组,还要定义大小
        result[0] = 0;
        result[1] = 1;
        for (int i =2; i <= n; i++) {
            result[i] = result[i - 1] + result[i - 2];
        }
        return result[n];
    }
};

70. 爬楼梯

简单题目,dp table如下,因为题目说了每次只能走一到两格,所以后一个的结果可以由-1和-2的结果推导出来,剩下的就和上面一摸一样;

cpp 复制代码
class Solution {
public:
    int climbStairs(int n) {
        if (n <= 1) return n;
        vector<int> result(n + 1);
        result[1] = 1;
        result[2] = 2;
        for (int i = 3; i <= n; i++) {
            result[i] = result[i - 2] + result[i - 1];
        }
        return result[n];
    }
};

746. 使用最小花费爬楼梯

简单题,和前面两个题差不多,要注意一点: 如果cost里面有十个元素,最后要去的是11层,因为到了第十个元素还要往上一层才是楼顶,这部分注意下就很容易了

cpp 复制代码
class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        int size = cost.size();
        vector<int> result(size + 1);
        result[0] = 0;
        result[1] = 0;
        for (int i = 2; i <= size; i++) { //这里的边界条件是要到楼顶,所以到了最后一层还要往上算一层
            result[i] = min(result[i-1] + cost[i-1], result[i-2] + cost[i - 2]);
        }
        return result[size];
    }
};
相关推荐
NAGNIP18 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队19 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja1 天前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶1 天前
算法 --- 字符串
算法
博笙困了1 天前
AcWing学习——差分
c++·算法
NAGNIP1 天前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP1 天前
大模型微调框架之LLaMA Factory
算法
echoarts1 天前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客1 天前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法