最长子序列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
相关文章推荐
- 【Python编程】 汉诺塔的递归实现
- Python用递归实现回文字符串的判断
- 斐波那契序列的递归和非递归实现方法
- 四则运算的递归python实现
- 最长回文子序列 java递归实现
- 使用python实现简单的序列密码
- python使用递归实现一个分形图形
- 人工智能:python 实现 第十一章,使用Pandas处理时间序列数据
- 人工智能:python 实现 第十一章,时间序列数据分片
- python 全排列 递归中的两种实现
- Python实现递归遍历文件夹并删除文件
- 0,1,3,6,10,15序列 递归实现!
- Python实现在给定整数序列中找到和为100的所有数字组合
- Python实现素数筛法与二分查找(递归)
- Python递归实现汉诺塔
- python二分查找算法的递归实现方法
- python 递归实现 汉诺塔
- python实现Collatz 序列
- python+opencv实现基于图片序列的三维重建
- 【Python学习日记】递归实现hanoi塔