算法训练营第五十二天|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. 最长重复子数组

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

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操作。理论上说不等也最起码有dp[j - 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;
    }
};

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

相关推荐
星火开发设计1 小时前
枚举类 enum class:强类型枚举的优势
linux·开发语言·c++·学习·算法·知识
嘴贱欠吻!7 小时前
Flutter鸿蒙开发指南(七):轮播图搜索框和导航栏
算法·flutter·图搜索算法
张祥6422889047 小时前
误差理论与测量平差基础笔记十
笔记·算法·机器学习
qq_192779877 小时前
C++模块化编程指南
开发语言·c++·算法
cici158749 小时前
大规模MIMO系统中Alamouti预编码的QPSK复用性能MATLAB仿真
算法·matlab·预编码算法
历程里程碑9 小时前
滑动窗口---- 无重复字符的最长子串
java·数据结构·c++·python·算法·leetcode·django
2501_9403152610 小时前
航电oj:首字母变大写
开发语言·c++·算法
CodeByV11 小时前
【算法题】多源BFS
算法
TracyCoder12311 小时前
LeetCode Hot100(18/100)——160. 相交链表
算法·leetcode
浒畔居11 小时前
泛型编程与STL设计思想
开发语言·c++·算法