最长公共子序列是动态规划基本题目,下面按照动态规划基本步骤解出来。可以参考July的教程:十分钟搞定LCS
def LCS_Len(X,Y):
m = len(X)
n = len(Y)
# C = zeros((m+1,n+1))#记录公共最长子串的矩阵
# flag = zeros((m+1,n+1)) #记录方向
C = [[0 for i in range(n+1)] for j in range(m+1)]
flag = [[0 for i in range(n+1)] for j in range(m+1)]
for i in arange(m):
for j in arange(n):
if X[i]==Y[j]:
C[i+1][j+1] = C[i][j]+1
flag[i+1][j+1] = 'ok'
elif C[i+1][j]>C[i][j+1]:
C[i+1][j+1] = C[i+1][j]
flag[i+1][j+1] = 'left'
else:
C[i+1][j+1] = C[i][j+1]
flag[i+1][j+1] ='up'
return C,flag
def printLCS(flag,X,i,j):
if i==0 or j==0:
return
if flag[i][j]=='ok':
printLCS(flag,X,i-1,j-1)
print(X[i-1],end='')
elif flag[i][j] == 'left':
printLCS(flag,X,i,j-1)
else:
printLCS(flag,X,i-1,j)
if __name__ == "__main__":
X = array(["A","B","C","B","D","A","B"])
Y = array(["B","D","C","A","B","A"])
c,flag = LCS_Len(X,Y)
for i in c:
print(i)
print('')
for j in flag:
print(j)
print('')
printLCS(flag,X,len(X),len(Y))
print('')
[0, 0, 0, 0, 0, 0, 0]
[0, 0, 0, 0, 1, 1, 1]
[0, 1, 1, 1, 1, 2, 2]
[0, 1, 1, 2, 2, 2, 2]
[0, 1, 1, 2, 2, 3, 3]
[0, 1, 2, 2, 2, 3, 3]
[0, 1, 2, 2, 3, 3, 4]
[0, 1, 2, 2, 3, 4, 4]
[0, 0, 0, 0, 0, 0, 0]
[0, 'up', 'up', 'up', 'ok', 'left', 'ok']
[0, 'ok', 'left', 'left', 'up', 'ok', 'left']
[0, 'up', 'up', 'ok', 'left', 'up', 'up']
[0, 'ok', 'up', 'up', 'up', 'ok', 'left']
[0, 'up', 'ok', 'up', 'up', 'up', 'up']
[0, 'up', 'up', 'up', 'ok', 'up', 'ok']
[0, 'ok', 'up', 'up', 'up', 'ok', 'up']
BCBA