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

1143.最长公共子序列

文章链接  |  题目链接  |  视频链接

C++解法

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()];
    }
};

Python解法

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        dp = [[0] * (len(text2)+1) for _ in range(len(text1)+1)]
        for i in range(1, len(text1)+1):
            for j in range(1, len(text2)+1):
                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[len(text1)][len(text2)]

1035.不相交的线

文章链接  |  题目链接  |  视频链接

C++解法

class Solution {
public:
    int maxUncrossedLines(vector& nums1, vector& nums2) {
        vector> dp (nums1.size() + 1, vector (nums2.size() + 1, 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;
                } else {
                    dp[i][j] = max(dp[i-1][j], dp[i][j-1]);
                }
            }
        }
        return dp[nums1.size()][nums2.size()];
    }
};

Python解法

class Solution:
    def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
        dp = [[0] * (len(nums2)+1) for _ in range(len(nums1)+1)]
        for i in range(1, len(nums1)+1):
            for j in range(1, len(nums2)+1):
                if nums1[i-1] == nums2[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[len(nums1)][len(nums2)]

53. 最大子序和

文章链接  |  题目链接  |  视频链接

C++解法

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];
        }
        return result;
    }
};

Python解法

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        if len(nums) == 0:
            return 0
        dp = [0] * len(nums)
        dp[0] = nums[0]
        result = dp[0]
        for i in range(1, len(nums)):
            dp[i] = max(dp[i-1] + nums[i], nums[i])
            if result < dp[i]:
                result = dp[i]
        return result

你可能感兴趣的:(代码随想录刷题训练营,算法)