算法训练营第五十二天|300.最长递增子序列 674. 最长连续递增序列 718. 最长重复子数组

目录

  • Leetcode300.最长递增子序列
  • [Leetcode674. 最长连续递增序列](#Leetcode674. 最长连续递增序列)
  • [Leetcode718. 最长重复子数组](#Leetcode718. 最长重复子数组)

Leetcode300.最长递增子序列

文章链接:代码随想录

题目链接:300.最长递增子序列

思路:数组存在就至少为一,dp元素初始化为1

cpp 复制代码
class Solution {
public:
    int lengthOfLIS(vector<int>& nums) {
        if (nums.size() == 1) return 1;
        vector<int> dp(nums.size(), 1);
        int result = 1;
        for (int i = 1; i < nums.size(); i++){
            for (int j = 0; j < i; j++){
                if (nums[i] > nums[j]) dp[i] = max(dp[i], dp[j] + 1);
            }
            result = result > dp[i] ? result : dp[i];
        }
        return result;
    }
};

Leetcode674. 最长连续递增序列

文章链接:代码随想录

题目链接:674. 最长连续递增序列

思路:连续的话,比较相邻元素即可。

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

Leetcode718. 最长重复子数组

文章链接:代码随想录

题目链接:718. 最长重复子数组

思路:二维数组,创建数组时多建一层是为了避免初始化,否则就得在循环前先初始化一遍dpi0和dp0j。

cpp 复制代码
class Solution {
public:
    int findLength(vector<int>& nums1, vector<int>& nums2) {
        vector<vector<int>> dp(nums1.size() + 1, vector<int>(nums2.size() + 1));
        int result = 0;
        for (int i = 1; i <= nums1.size(); i++){
            for (int j = 1; j <= nums2.size(); j++){
                if (nums1[i - 1] == nums2[j - 1]){
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                }
                result = result > dp[i][j] ? result : dp[i][j];
            }
        }
        return result;
    }
};

滚动(一维)数组,不等要有赋0操作。理论上说不等也最起码有dpj - 1个子字符串相等,但是这个值会影响下一层的判断,若下一层的两元素相等,则会得出错误结果,故不等需要赋0。而每个相等字符串的长度都会有一个元素记录过,无需担心漏记。

和背包问题同样 j 的后序遍历是为了避免错误累加。

cpp 复制代码
class Solution {
public:
    int findLength(vector<int>& nums1, vector<int>& nums2) {
        vector<int> dp(nums2.size() + 1);
        int result = 0;
        for (int i = 1; i <= nums1.size(); i++){
            for (int j = nums2.size(); j > 0; j--){
                if (nums1[i - 1] == nums2[j - 1]){
                    dp[j] = dp[j - 1] + 1;
                }else dp[j] = 0;
                result = result > dp[j] ? result : dp[j];
            }
        }
        return result;
    }
};

第五十二天打卡,加油!!!

相关推荐
加宝的起点雷达3 小时前
40 条候选里 38 条来自同一个源,主卡整屏重样
人工智能·算法·创业
秋天的怀念_David3 小时前
算法一千零一夜 · 第二十六夜 协议的母语
java·spring boot·算法
闻缺陷则喜何志丹6 小时前
【C++特性】四种类型转
c++·算法·类型转换
喵本喵叁肆6 小时前
用 Boosting 把弱隐私算法炼成强隐私算法(英文原题:Boosting and Differential Privacy (FOCS 2010))
算法·集成学习·boosting
青梅味猪大肠6 小时前
【操作系统-60】临近适应算法
java·linux·开发语言·嵌入式硬件·算法·操作系统
其实防守也摸鱼21 小时前
个人学习 Pwn 思路:从基础到漏洞利用的进阶路径
大数据·前端·人工智能·chrome·算法·安全·网络安全
Nuanyt1 天前
LeetCode Hot 100 链表专题(五)· 2 题(Java)
java·算法·leetcode·链表