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];
    }
};
相关推荐
yaoh.wang1 天前
力扣(LeetCode) 13: 罗马数字转整数 - 解法思路
python·程序人生·算法·leetcode·面试·职场和发展·跳槽
T1ssy1 天前
布隆过滤器:用概率换空间的奇妙数据结构
算法·哈希算法
hetao17338371 天前
2025-12-12~14 hetao1733837的刷题笔记
数据结构·c++·笔记·算法
鲨莎分不晴1 天前
强化学习第五课 —— A2C & A3C:并行化是如何杀死经验回放
网络·算法·机器学习
搞科研的小刘选手1 天前
【ISSN/ISBN双刊号】第三届电力电子与人工智能国际学术会议(PEAI 2026)
图像处理·人工智能·算法·电力电子·学术会议
拉姆哥的小屋1 天前
从混沌到秩序:条件扩散模型在图像转换中的哲学与技术革命
人工智能·算法·机器学习
Sammyyyyy1 天前
DeepSeek v3.2 正式发布,对标 GPT-5
开发语言·人工智能·gpt·算法·servbay
QQ 19226381 天前
探索储能双向 DCDC 变换器:双向 Buck - Boost 电路仿真之旅
深度优先
sin_hielo1 天前
leetcode 2110
数据结构·算法·leetcode
Jay20021111 天前
【机器学习】33 强化学习 - 连续状态空间(DQN算法)
人工智能·算法·机器学习