算法训练营第五十二天|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;
    }
};

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

相关推荐
这可就有点麻烦了8 分钟前
强化学习笔记之【TD3算法】
linux·笔记·算法·机器学习
苏宸啊13 分钟前
顺序表及其代码实现
数据结构·算法
lin zaixi()17 分钟前
贪心思想之——最大子段和问题
数据结构·算法
FindYou.17 分钟前
C - Separated Lunch
算法·深度优先
夜雨翦春韭23 分钟前
【代码随想录Day30】贪心算法Part04
java·数据结构·算法·leetcode·贪心算法
Kent_J_Truman34 分钟前
【平方差 / C】
算法
一直学习永不止步35 分钟前
LeetCode题练习与总结:H 指数--274
java·数据结构·算法·leetcode·数组·排序·计数排序
Amor风信子1 小时前
华为OD机试真题---跳房子II
java·数据结构·算法
戊子仲秋1 小时前
【LeetCode】每日一题 2024_10_2 准时到达的列车最小时速(二分答案)
算法·leetcode·职场和发展
邓校长的编程课堂1 小时前
助力信息学奥赛-VisuAlgo:提升编程与算法学习的可视化工具
学习·算法