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];
    }
};
相关推荐
Elias不吃糖1 天前
LeetCode每日一练(209, 167)
数据结构·c++·算法·leetcode
铁手飞鹰1 天前
单链表(C语言,手撕)
数据结构·c++·算法·c·单链表
悦悦子a啊1 天前
项目案例作业(选做):使用文件改造已有信息系统
java·开发语言·算法
小殊小殊1 天前
【论文笔记】知识蒸馏的全面综述
人工智能·算法·机器学习
无限进步_1 天前
C语言动态内存管理:掌握malloc、calloc、realloc和free的实战应用
c语言·开发语言·c++·git·算法·github·visual studio
im_AMBER1 天前
AI井字棋项目开发笔记
前端·笔记·学习·算法
Wadli1 天前
项目2 |内存池1|基于哈希桶的多种定长内存池
算法
TT哇1 天前
【BFS 解决拓扑排序】3. ⽕星词典(hard)
redis·算法·宽度优先
橘颂TA1 天前
【剑斩OFFER】算法的暴力美学——判定字符是否唯一
算法·c/c++·结构与算法
ModestCoder_1 天前
PPO-clip算法在Gymnasium的Pendulum环境实现
人工智能·算法·机器人·具身智能