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];
    }
};
相关推荐
NAGNIP10 小时前
大模型框架性能优化策略:延迟、吞吐量与成本权衡
算法
美团技术团队11 小时前
LongCat-Flash:如何使用 SGLang 部署美团 Agentic 模型
人工智能·算法
Fanxt_Ja16 小时前
【LeetCode】算法详解#15 ---环形链表II
数据结构·算法·leetcode·链表
侃侃_天下16 小时前
最终的信号类
开发语言·c++·算法
茉莉玫瑰花茶16 小时前
算法 --- 字符串
算法
博笙困了16 小时前
AcWing学习——差分
c++·算法
NAGNIP16 小时前
认识 Unsloth 框架:大模型高效微调的利器
算法
NAGNIP16 小时前
大模型微调框架之LLaMA Factory
算法
echoarts16 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Python技术极客16 小时前
一款超好用的 Python 交互式可视化工具,强烈推荐~
算法