代码随想录day53|1143. 最长公共子序列1035. 不相交的线53. 最大子数组和

1143. 最长公共子序列

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        #dp[i][j]数组表示text1以i索引结尾,text2以j索引结尾的最长公共子序列
        # result = 0 
        dp = [[0]*len(text2) for _ in range(len(text1))]
        for i in range(len(text1)):
            if text1[i] == text2[0]:
                for j in range(i,len(text1)):
                    dp[j][0] = 1
                # result= 1 
                break               
        for i in range(len(text2)):
            if text2[i] == text1[0]:
                for j in range(i,len(text2)):
                    dp[0][j] = 1
                # result= 1 
                break 
        for i in range(1,len(text1)):
            for j in range(1,len(text2)):
                temp = 0
                if text1[i]==text2[j]:
                    temp = dp[i-1][j-1]+1
                dp[i][j] = max(dp[i-1][j],dp[i][j-1],temp)
                # result = max(result,dp[i][j] )
        return dp[len(text1)-1][len(text2)-1]

1035. 不相交的线

class Solution:
    def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:
        dp = [[0]*len(nums2) for _ in range(len(nums1))]
        for i in range(len(nums1)):
            if nums1[i] == nums2[0]:
                for j in range(i,len(nums1)):
                    dp[j][0] = 1
                # result= 1 
                break               
        for i in range(len(nums2)):
            if nums2[i] == nums1[0]:
                for j in range(i,len(nums2)):
                    dp[0][j] = 1
                # result= 1 
                break 
        for i in range(1,len(nums1)):
            for j in range(1,len(nums2)):
                temp = 0
                if nums1[i]==nums2[j]:
                    temp = dp[i-1][j-1]+1
                dp[i][j] = max(dp[i-1][j],dp[i][j-1],temp)
                # result = max(result,dp[i][j] )
        return dp[len(nums1)-1][len(nums2)-1]

53. 最大子数组和

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        # result = float('-inf')
        # count = 0
        # for i in range(len(nums)):
        #     count += nums[i]
        #     if count> result:
        #         result =count
        #     if count < 0 :
        #         count =0
        # return result
        ## 动态规划方法
        dp = [0] * len(nums)
        dp[0] = nums[0]
        for i in range(1,len(nums)):
            dp[i] = max(nums[i],dp[i-1]+nums[i])
        return max(dp)

你可能感兴趣的:(算法,leetcode,职场和发展)