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

Leecode 300.最长递增子序列

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

题目类型:最长子序列

class Solution {
public:
    int lengthOfLIS(vector& nums) {
        int n = nums.size();
        // dp[i]代表到第i个元素时的最长子序列长度
        vector 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)官网 - 全球极客挚爱的技术成长平台

题目类型:最长子序列

class Solution {
public:
    int findLengthOfLCIS(vector& 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)官网 - 全球极客挚爱的技术成长平台

题目类型:最长子序列

class Solution {
public:
    int findLength(vector& nums1, vector& nums2) {
        int m = nums1.size(), n = nums2.size();
        int result = 0;
        vector> dp(m + 1, vector(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;
    }
};

你可能感兴趣的:(算法训练营,算法,leetcode,数据结构)