标签:str 记录 ext1 pre 循环 ons sub 规划 双层
经典的动态规划题目:最长公共子序列(Longest Common Subsequence),使用二维数组记录,双层循环。
1 class Solution: 2 def longestCommonSubsequence(self, text1: str, text2: str) -> int: 3 n1,n2 = len(text1),len(text2) 4 if n1 == 0 or n2 == 0: 5 return 0 6 dp = [[0 for _ in range(n2+1)]for _ in range(n1+1)] 7 for i in range(1,n1+1): 8 for j in range(1,n2+1): 9 if text1[i-1] == text2[j-1]: 10 dp[i][j] = dp[i-1][j-1] + 1 11 else: 12 dp[i][j] = max(dp[i][j-1],dp[i-1][j]) 13 return dp[n1][n2]
标签:str 记录 ext1 pre 循环 ons sub 规划 双层
原文地址:https://www.cnblogs.com/asenyang/p/11920710.html