代码随想录二刷 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];
    }
};
相关推荐
luckys.one1 天前
第9篇:Freqtrade量化交易之config.json 基础入门与初始化
javascript·数据库·python·mysql·算法·json·区块链
~|Bernard|1 天前
在 PyCharm 里怎么“点鼠标”完成指令同样的运行操作
算法·conda
战术摸鱼大师1 天前
电机控制(四)-级联PID控制器与参数整定(MATLAB&Simulink)
算法·matlab·运动控制·电机控制
Christo31 天前
TFS-2018《On the convergence of the sparse possibilistic c-means algorithm》
人工智能·算法·机器学习·数据挖掘
好家伙VCC1 天前
数学建模模型 全网最全 数学建模常见算法汇总 含代码分析讲解
大数据·嵌入式硬件·算法·数学建模
liulilittle1 天前
IP校验和算法:从网络协议到SIMD深度优化
网络·c++·网络协议·tcp/ip·算法·ip·通信
bkspiderx1 天前
C++经典的数据结构与算法之经典算法思想:贪心算法(Greedy)
数据结构·c++·算法·贪心算法
中华小当家呐1 天前
算法之常见八大排序
数据结构·算法·排序算法
沐怡旸1 天前
【算法--链表】114.二叉树展开为链表--通俗讲解
算法·面试
一只懒洋洋1 天前
K-meas 聚类、KNN算法、决策树、随机森林
算法·决策树·聚类