class Solution: DEF the LCS (Self, A, B): IF Not A or Not B: # boundary processing return 0 DP = [[0 for _ in Range (len (B) + 1'd)] for _ in Range (len ( a) + 1'd)] # state definition, dp [i] [j] denotes the current length of the longest common for I in Range (. 1, len (a) + 1'd): # traversal a sequence for J in Range (. 1, len (B) + 1'd): # traversal sequence B, the time complexity is N2 IFA [-I. 1] == B [-J. 1]: # If the two values are equal at this time DP [I] [J] DP = [. 1-I] [J-. 1] +. 1 # state transition is a pre time state plus. 1 the else : # are not equal, then DP [I] [J] = max (DP [I] [J-. 1], DP [I-. 1] [J]) # state at the current time, for the first two the larger the value of the time Print (B) self.printDP (DP) return DP [-1] [-. 1] # optimal solution is the last state value DEF printDP (Self, DP): # Print transient for I in Range (len (dp)): for Jin Range (len (DP [I])): Print (DP [I] [J], End = ' ' ) Print () IF the __name__ == ' __main__ ' : Solution = Solution () A = [. 1, 2, . 3,. 5, 2,. 1 ] B = [. 3, 2,. 1,. 4,. 7 ] RES = solution.LCS (A, B) Print ( ' longest common subsequence length: ' , RES)
The results are as follows: [3,2,1] is the longest common subsequence