Day14 动态规划(3)

一.746. 使用最小花费爬楼梯

FS+记忆化搜索优化:

cpp 复制代码
const int N = 1010;


class Solution {
public:
    int mem[N];

    int dfs(vector<int>& cost, int x){
        if(mem[x]) return mem[x];
        int sum = 0;

        if(x == 0 || x == 1) return 0;
        else{
            sum = min(dfs(cost, x - 1) + cost[x - 1], dfs(cost, x - 2) + cost[x - 2]);
        }
        mem[x] = sum;
        return sum;
    }

    int minCostClimbingStairs(vector<int>& cost) {
        int n = cost.size();

        int ans = dfs(cost, n);
        return ans;
    }
};

动态规划:

cpp 复制代码
class Solution {
public:
    int minCostClimbingStairs(vector<int>& cost) {
        const int N = 1010;
        int n = cost.size();
        int f[N];
        for(int i = 2; i <= n; i++){
            f[i] = min(f[i - 1] + cost[i - 1], f[i - 2] + cost[i - 2]);
        }
        return f[n];
    }
};

二.300. 最长递增子序列

cpp 复制代码
const int N = 2510;

class Solution {
public:
    int mem[N];

    int dfs(vector<int>& nums, int x){
        if(mem[x]) return mem[x];
        int ans = 1;
        for(int i = 0; i < x; i++){
            if(nums[i] < nums[x]){
                ans = max(ans, dfs(nums, i) + 1);
            }
        }
        mem[x] = ans;
        return ans;
    }

    int lengthOfLIS(vector<int>& nums) {
        int n = nums.size();
        int ans = INT_MIN;
        int f[N];
        // for(int i = 0; i < n; i++){
        //     ans = max(ans, dfs(nums, i));
        // }
        // return ans;    

        for(int i = 0; i < n; i++){
            f[i] = 1;
            for(int j = 0; j < i; j++){
                if(nums[j] < nums[i]){
                    f[i] = max(f[i], f[j] + 1);
                }
            }
        }
        return f[n];
    }
};
相关推荐
2401_8582861138 分钟前
OS26.【Linux】进程程序替换(下)
linux·运维·服务器·开发语言·算法·exec·进程
张同学的IT技术日记1 小时前
【奇妙的数据结构世界】用图像和代码对队列的使用进行透彻学习 | C++
算法
极客BIM工作室1 小时前
强化学习算法分类与介绍(含权重更新公式)
算法·分类·数据挖掘
KarrySmile1 小时前
Day8--HOT100--160. 相交链表,206. 反转链表,234. 回文链表,876. 链表的中间结点
数据结构·算法·链表·双指针·快慢指针·hot100·灵艾山茶府
luckycoding1 小时前
1424. 对角线遍历 II
算法·leetcode·职场和发展
CoovallyAIHub1 小时前
基于ICR损失与SVMLP数据集:小目标检测新突破,车牌检测准确率显著提升
深度学习·算法·计算机视觉
鲸鱼24011 小时前
贝叶斯笔记
人工智能·算法·机器学习
刃神太酷啦2 小时前
Linux 常用指令全解析:从基础操作到系统管理(1w字精简版)----《Hello Linux!》(2)
linux·运维·服务器·c语言·c++·算法·leetcode
努力找工作的OMArmy2 小时前
力扣498 对角线遍历
算法·leetcode·职场和发展
不知名。。。。。。。。4 小时前
算法 ---哈希表
数据结构·算法·散列表