题目地址http://zju.acmclub.com/index.php?app=problem_title&id=1&problem_id=1132
采用动态规划策略,先初始化二维数组的第0行和第0列,然后从第一行或第一列数组开始,依次填满数组,并记录箭头方向。
ps:此题要求输出最长子序列的长度,即输出最终数组的右下角元素即可,若要求输出子序列则需要按照箭头走,只输出指向左上角的箭头。
为了按序输出,使用递归即可。
python代码:
#coding=utf-8
def Matrix(rows,cols):
matrix = [[[0,'#'] for col in range(cols+1)] for row in range(rows+1)]
return matrix
def printf(lst,str1,str2):
(rows,cols)=(len(str1),len(str2))
print ' '*6,
for tmp in str2:
print '%s ' % tmp,
print
print ' '*2,
for j in range(cols+1):
print '%d:%s' % (lst[0][j][0],lst[0][j][1]),
print
for i in range(1,rows+1):
print '%s ' % str1[i-1],
for j in range(cols+1):
print '%d:%s' % (lst[i][j][0],lst[i][j][1]),
print
while True:
[x,y]=raw_input().split()
(m,n)=(len(x),len(y))
mat = Matrix(m,n)#已经经过初始化
for i in range(1,m+1):
for j in range(1,n+1):
#print "i=%d,j=%d" %(i,j)
if x[i-1]==y[j-1]:
mat[i][j][0]=mat[i-1][j-1][0]+1
mat[i][j][1]='↖'
elif mat[i-1][j][0]>=mat[i][j-1][0]:
mat[i][j][0]=mat[i-1][j][0]
mat[i][j][1]='↑'
else:
mat[i][j][0]=mat[i][j-1][0]
mat[i][j][1]='←'
#printf(mat,x,y)
print mat[m][n][0]