算法训练营第四十天(9.1)| 动态规划Part11:最长子序列系列

Leecode 300.最长递增子序列

题目地址:力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

题目类型:最长子序列

cpp 复制代码
class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        int n = nums.size();
        // dp[i]代表到第i个元素时的最长子序列长度
        vector<int> dp(n, 1);
        int res = 1;
        for (int i = 1; i < n; ++i) {
            for (int j = 0; j < i; ++j) {
                if (nums[i] > nums[j]) dp[i] = max(dp[i], dp[j] + 1);
            }
            res = max(res, dp[i]);
        }
        return res;
    }
};

Leecode 674.最长连续递增序列

题目地址:​​​​​​​力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

题目类型:最长子序列

cpp 复制代码
class Solution {
public:
    int findLengthOfLCIS(vector<int>& nums) {
        int n = nums.size();
        int res = 1, cur = 1;
        for (int i = 1; i < n; ++i) {
            if (nums[i] > nums[i - 1]) {
                cur++;
                res = max(cur, res);
            }
            else {
                cur = 1;
            }
        }
        return res;
    }
};

Leecode 718.最长重复子数组

题目地址:​​​​​​​力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

题目类型:最长子序列

cpp 复制代码
class Solution {
public:
    int findLength(vector<int>& nums1, vector<int>& nums2) {
        int m = nums1.size(), n = nums2.size();
        int result = 0;
        vector<vector<int>> dp(m + 1, vector<int>(n + 1));
        for (int i = 1; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (nums1[i - 1] == nums2[j - 1]) dp[i][j] = dp[i - 1][j - 1] + 1;
                if (dp[i][j] > result) result = dp[i][j];
            }
        }
        return result;
    }
};
相关推荐
原来是猿22 分钟前
蓝桥备赛(四)- 数组(下)
开发语言·数据结构·c++·算法
ephemerals__34 分钟前
【数据结构进阶】哈希表
数据结构·算法·散列表
阿巴~阿巴~1 小时前
关于回溯算法中的剪枝是否需要for循环的总结归纳
数据结构·c++·算法·深度优先·剪枝
一只_程序媛1 小时前
【leetcode hot 100 42】接雨水
java·算法·leetcode
普通young man2 小时前
哈希封装unordered_map/unordered_set
算法·哈希算法
Dovis(誓平步青云)2 小时前
【数据结构】二叉树(门槛极低的系统理解)
c语言·数据结构·算法
朔北之忘 Clancy2 小时前
2022 年 12 月青少年软编等考 C 语言五级真题解析
c语言·开发语言·c++·学习·算法·青少年编程·题解
一只码代码的章鱼2 小时前
数据结构与算法-图论-最短路-floyd扩展
算法·图论
跳动的梦想家h2 小时前
hot100-矩阵
java·算法·矩阵
Liu_Meihao2 小时前
【算法】796. 子矩阵的和
算法