动态规划算法求最长公共子序列问题python完整代码
时间: 2023-07-28 10:12:06 浏览: 93
下面是Python的完整代码:
```python
def lcs(X, Y):
m = len(X)
n = len(Y)
L = [[None]*(n+1) for i in range(m+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])
index = L[m][n]
lcs = [""] * (index+1)
lcs[index] = ""
i = m
j = n
while i > 0 and j > 0:
if X[i-1] == Y[j-1]:
lcs[index-1] = X[i-1]
i-=1
j-=1
index-=1
elif L[i-1][j] > L[i][j-1]:
i-=1
else:
j-=1
return "".join(lcs)
X = "AGGTAB"
Y = "GXTXAYB"
print("LCS of", X, "and", Y, "is", lcs(X, Y))
```
其中,X和Y分别为两个字符串,lcs函数返回它们的最长公共子序列。该算法的时间复杂度为O(mn),其中m和n分别为X和Y的长度。
阅读全文