代码随想录二刷 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];
    }
};
相关推荐
czhaii4 分钟前
GB2312简体中文编码表
单片机·算法
8Qi813 分钟前
LeetCode 121 & 122:股票买卖问题(DP 对比题解)✅
算法·leetcode·职场和发展·动态规划
一只齐刘海的猫24 分钟前
【Leetcode】 接雨水
java·算法·leetcode
南境十里·墨染春水41 分钟前
讲讲移动语义
算法
西凉的悲伤1 小时前
Guava类库——Range连续区间
java·算法·guava
菜菜的顾清寒1 小时前
力扣HOT(100)54多维动态规划-最长公共子序列
算法·leetcode·动态规划
随意起个昵称1 小时前
线性dp-LIS题目3(合唱队形)
算法
小六学编程1 小时前
二分查找详解:从普通二分到左右边界
算法·c/c++
wayz111 小时前
Volume:PVO(百分比成交量震荡指标)技术指标详解
算法·金融·数据分析·量化交易·特征工程
毕竟是shy哥1 小时前
PromptHash:基于亲和提示协同学习的自适应哈希检索跨模态算法
学习·算法·哈希算法