本文主要是介绍第九章 动态规划part14,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1143. 最长公共子序列
class Solution:def longestCommonSubsequence(self, text1: str, text2: str) -> int:n1 = len(text1)n2 = len(text2)dp = [[0]*(n2+1) for _ in range(n1+1)]for i in range(1,n1+1):for j in range(1,n2+1):if (text1[i - 1] == text2[j - 1]):dp[i][j] = dp[i - 1][j - 1] + 1else:dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])return dp[n1][n2]
1035. 不相交的线
class Solution:def maxUncrossedLines(self, nums1: List[int], nums2: List[int]) -> int:n1 = len(nums1)n2 = len(nums2)dp = [[0]*(n2+1) for _ in range(n1+1)]for i in range(1,n1+1):for j in range(1,n2+1):if (nums1[i - 1] == nums2[j - 1]):dp[i][j] = dp[i - 1][j - 1] + 1else:dp[i][j] = max(dp[i - 1][j], dp[i][j - 1])return dp[n1][n2]
53. 最大子数组和
class Solution:def maxSubArray(self, nums: List[int]) -> int:n = len(nums)dp = [0] * (n)result = float('-inf')dp[0] = nums[0]result = dp[0]if n == 1:return nums[0]for i in range(1,n):dp[i] = max(dp[i - 1] + nums[i], nums[i])result = max(result,dp[i])return result
这篇关于第九章 动态规划part14的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!