您的位置:首页 > 编程语言 > Python开发

最长子序列python递归实现

2018-01-10 23:48 246 查看
def lcs1(A, B):
# 普通递归
if not(A and B):
return ''
elif A[-1] == B[-1]:
return lcs1(A[:-1], B[:-1]) + A[-1]
else:
if len(lcs1(A[:-1], B)) > len(lcs1(A, B[:-1])):
return lcs1(A[:-1], B)
else:
return lcs1(A, B[:-1])

chart = {}
def lcs2(A, B):
# 动态规划版
global chart
if (A, B) in chart.keys():
return chart.get((A, B))
else:
if not(A and B):
return ''
elif A[-1] == B[-1]:
return lcs2(A[:-1], B[:-1]) + A[-1]
else:
if len(lcs2(A[:-1], B)) > len(lcs2(A, B[:-1])):
chart.update({(A[:-1], B): lcs2(A[:-1], B)})
return lcs2(A[:-1], B)
else:
chart.update({(A,B[:-1]): lcs2(A, B[:-1])})
return lcs2(A, B[:-1])

print(lcs1('educatiSDWonal', 'advSDWantage'))
# print(chart)

关于原理部分,可查看http://blog.csdn.net/lisonglisonglisong/article/details/41548557
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息