代码随想录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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值