代码随想录算法训练营 day53|1143.最长公共子序列、1035.不相交的线、53. 最大子序和

一、1143.最长公共子序列

力扣题目链接

class Solution {
public:
    int longestCommonSubsequence(string text1, string text2) {
        vector> dp(text1.size() + 1, vector(text2.size() + 1, 0));
        for (int i = 1; i <= text1.size(); i++) {
            for (int j = 1; j <= text2.size(); j++) {
                if (text1[i - 1] == text2[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[text1.size()][text2.size()];
    }
};

二、1035.不相交的线

力扣题目链接

class Solution {
public:
    int maxUncrossedLines(vector& A, vector& B) {
        vector> dp(A.size() + 1, vector(B.size() + 1, 0));
        for (int i = 1; i <= A.size(); i++) {
            for (int j = 1; j <= B.size(); j++) {
                if (A[i - 1] == B[j - 1]) {
                    dp[i][j] = dp[i - 1][j - 1] + 1;
                } else {
                    dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
                }
            }
        }
        return dp[A.size()][B.size()];
    }
};

三、53. 最大子序和

力扣题目链接

class Solution {
public:
    int maxSubArray(vector& nums) {
        if (nums.size() == 0) return 0;
        vector dp(nums.size());
        dp[0] = nums[0];
        int result = dp[0];
        for (int i = 1; i < nums.size(); i++) {
            dp[i] = max(dp[i - 1] + nums[i], nums[i]); // 状态转移公式
            if (dp[i] > result) result = dp[i]; // result 保存dp[i]的最大值
        }
        return result;
    }
};

 

你可能感兴趣的:(待仔细回顾,算法,leetcode,数据结构)