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];
    }
};
相关推荐
爱刷碗的苏泓舒2 小时前
PPP-AR 中的参考星选取:数学原理、评价指标与切换处理
算法·gnss·模糊度固定·ppp-ar·星间单差·参考星·卫星端偏差
烬羽5 小时前
递归老写崩?一个"退回"公式,把回溯题变成填空题
javascript·深度学习·算法
闪电悠米5 小时前
力扣hot100-41.缺失的第一个正数-原地哈希详解
数据结构·算法·哈希算法
星空露珠6 小时前
28种颜色对应名称,
开发语言·数据库·算法·游戏·lua
QXWZ_IA8 小时前
桥梁数字孪生怎么落地?
人工智能·科技·算法·智能硬件·政务
Kel8 小时前
输出层与反分词(Output Layer & Detokenization)
人工智能·算法·架构
陕西企来客8 小时前
2026年7月技术好GEO优化方案:算法适配与内容策略
人工智能·算法·机器学习·技术好geo优化
风栖柳白杨8 小时前
【面试】AI算法工程师_空白自测版本
人工智能·算法·面试
闪电悠米9 小时前
力扣hot100-73.矩阵置零-标记数组详解
算法·leetcode·矩阵
栋***t10 小时前
从“纸质试卷”到“AI智能组卷”,麦塔在线考试系统如何重构出题逻辑?
java·大数据·人工智能·算法·重构