LCS问题陈述:给定两个序列,找出两个序列中存在的最长子序列的长度。子序列是以相同的相对顺序出现,但不一定是连续的序列。例如,“ abc”,“ abg”,“ bdf”,“ aeg”,“ acefg”等是“ abcdefg”的子序列。因此,长度为n的字符串具有2 ^ n个不同的可能子序列。
这是一个经典的计算机科学问题,是diff(文件比较程序,输出两个文件之间的差异)的基础,并已在生物信息学中得到应用。
例子:
输入序列“ ABCDGH”和“ AEDFHR”的LCS为长度3的“ ADH”。
输入序列“ AGGTAB”和“ GXTXAYB”的LCS是长度为4的“ GTAB”。
令输入序列分别为长度[m]和[n]的X [0..m-1]和Y [0..n-1]。并令L(X [0..m-1],Y [0..n-1])为两个序列X和Y的LCS的长度。以下是L(X [0 … m-1],Y [0..n-1])。
如果两个序列的最后一个字符匹配(或X [m-1] == Y [n-1]),则
L(X [0..m-1],Y [0..n-1])= 1 + L(X [0..m-2],Y [0..n-2])
如果两个序列的最后一个字符都不匹配(或X [m-1]!= Y [n-1]),则
L(X [0..m-1],Y [0..n-1])= MAX(L(X [0..m-2],Y [0..n-1]),L( X [0..m-1],Y [0..n-2])
# A Naive recursive Python implementation of LCS problem
def lcs(X, Y, m, n):
if m == 0 or n == 0:
return 0;
elif X[m-1] == Y[n-1]:
return 1 + lcs(X, Y, m-1, n-1);
else:
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
# Driver program to test the above function
X = "AGGTAB"
Y = "GXTXAYB"
print ("Length of LCS is ", lcs(X, Y, len(X), len(Y)))
Length of LCS is 4
以下是LCS问题的列表实现。
# Dynamic Programming implementation of LCS problem
def lcs(X, Y):
# find the length of the strings
m = len(X)
n = len(Y)
# declaring the array for storing the dp values
L = [[None]*(n + 1) for i in range(m + 1)]
"""Following steps build L[m + 1][n + 1] in bottom up fashion
Note: L[i][j] contains length of LCS of X[0..i-1]
and Y[0..j-1]"""
for i in range(m + 1):
for j in range(n + 1):
if i == 0 or j == 0 :
L[i][j] = 0
elif X[i-1] == Y[j-1]:
L[i][j] = L[i-1][j-1]+1
else:
L[i][j] = max(L[i-1][j], L[i][j-1])
# L[m][n] contains the length of LCS of X[0..n-1] & Y[0..m-1]
return L[m][n]
# end of function lcs
# Driver program to test the above function
X = "AGGTAB"
Y = "GXTXAYB"
print("Length of LCS is ", lcs(X, Y))
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Length of LCS is 4
请参考有关动态编程的完整文章。设置4(最长公共子序列)以获取更多详细信息!