代码随想录二刷 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];
    }
};
相关推荐
aaaameliaaa1 天前
字符函数和字符串函数
c语言·笔记·算法
城管不管1 天前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
月疯1 天前
二分法算法(水平等分图形面积)
算法
豆瓣鸡1 天前
算法日记 - Day3
java·开发语言·算法
白白白小纯1 天前
算法篇—反转链表
c语言·数据结构·算法·leetcode
Achou.Wang1 天前
深入理解go语言-第5章 并发编程——Go的灵魂
大数据·算法·golang
The Chosen One9851 天前
高进度算法模板速记(待完善)
java·前端·算法
土豆.exe1 天前
Fastjson2 2.0.53 哈希碰撞 RCE:从原理到三种打法
算法·哈希算法
黄河123长江1 天前
有限Abel群的结构()
算法
Jerry1 天前
LeetCode 92. 反转链表 II
算法