Dynamic Programming | Set 4 (Longest Common Subsequence)
首先来看什么是最长公共子序列:给定两个序列,找到两个序列中均存在的最长公共子序列的长度。子序列需要以相关的顺序呈现,但不必连续。例如,“abc”, “abg”, “bdf”, “aeg”, ‘”acefg”等都是“abcdefg”的子序列。因此,一个长度为n的序列拥有2^n中可能的子序列(序列中的每一个元素只有选或者不选两种可能,因此是2^n)。
Example:
LCS for input Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for input Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.
该问题最普通的解法是对两个给定序列分别生成所有子序列,然后找到最长的匹配的子序列。这样的解法是指数复杂度的,显然不是我们需要的。我们来看该问题是如何拥有动态规划问题的重要性质的。
1 Optimal Substructure:
假设输入序列分别为长度为m的X[0..m-1]和长度为n的Y[0..n-1],令L(X[0..m-1], Y[0..n-1])为序列X、Y的最长公共子序列的长度,如下为L(X[0..m-1], Y[0..n-1])的递归定义:
If last characters of both sequences match (or X[m-1] == Y[n-1]) then
L(X[0..m-1], Y[0..n-1]) = 1 + L(X[0..m-2], Y[0..n-2])
If last characters of both sequences do not match (or X[m-1] != Y[n-1]) then
L(X[0..m-1], Y[0..n-1]) = MAX ( L(X[0..m-2], Y[0..n-1]), L(X[0..m-1], Y[0..n-2])
例子:
1) Consider the input strings “AGGTAB” and “GXTXAYB”. Last characters match for the strings. So length of LCS can be written as:
L(“AGGTAB”, “GXTXAYB”) = 1 + L(“AGGTA”, “GXTXAY”)
2) Consider the input strings “ABCDGH” and “AEDFHR. Last characters do not match for the strings. So length of LCS can be written as:
L(“ABCDGH”, “AEDFHR”) = MAX ( L(“ABCDG”, “AEDFHR”), L(“ABCDGH”, “AEDFH”) )
因此,LCS问题具有最优子结构性质,可以使用求解子问题的方案来解决。
2 Overlapping Subproblems:
如下是LCS问题的递归求解程序,该实现遵循了上面的递归结构:
/* A Naive recursive implementation of LCS problem */
#include<stdio.h>
#include<stdlib.h> int max(int a, int b); /* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs( char *X, char *Y, int m, int n )
{
if (m == 0 || n == 0)
return 0;
if (X[m-1] == Y[n-1])
return 1 + lcs(X, Y, m-1, n-1);
else
return max(lcs(X, Y, m, n-1), lcs(X, Y, m-1, n));
} /* Utility function to get max of 2 integers */
int max(int a, int b)
{
return (a > b)? a : b;
} /* Driver program to test above function */
int main()
{
char X[] = "AGGTAB";
char Y[] = "GXTXAYB"; int m = strlen(X);
int n = strlen(Y); printf("Length of LCS is %d\n", lcs( X, Y, m, n ) ); getchar();
return 0;
}
以上程序的时间复杂度在最坏情况下是O(2^n),最坏情况是X与Y中的所有字符均不匹配,也就是说LCS的长度为0。
根据上面的实现,如下是当输入序列为“AXYT”和“AYZX”时的部分递归树:
不难发现,lcs(“AXY”, “AYZ”) 被计算了2次。如果我们画出完整的递归树,会找到更多被重复计算的子问题。因此,该问题具备重叠子结构性质,可以通过Memoization或者Tabulation来避免重复计算。下面是LCS问题的Tabulation实现。
/* Dynamic Programming implementation of LCS problem */
#include<stdio.h>
#include<stdlib.h> int max(int a, int b); /* Returns length of LCS for X[0..m-1], Y[0..n-1] */
int lcs( char *X, char *Y, int m, int n )
{
int L[m+1][n+1];
int i, j; /* Following steps build L[m+1][n+1] in bottom up fashion. Note
that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
for (i=0; i<=m; i++)
{
for (j=0; j<=n; j++)
{
if (i == 0 || j == 0)
L[i][j] = 0; else if (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]);
}
} /* L[m][n] contains length of LCS for X[0..n-1] and Y[0..m-1] */
return L[m][n];
} /* Utility function to get max of 2 integers */
int max(int a, int b)
{
return (a > b)? a : b;
} /* Driver program to test above function */
int main()
{
char X[] = "AGGTAB";
char Y[] = "GXTXAYB"; int m = strlen(X);
int n = strlen(Y); printf("Length of LCS is %d\n", lcs( X, Y, m, n ) ); getchar();
return 0;
}
以上实现的时间复杂度为O(mn),相比原始递归求解的最坏情况要好太多了。
上面的程序只是返回了LCS的长度,可以参照该文章来打印LCS Printing Longest Common Subsequence 。
Dynamic Programming | Set 4 (Longest Common Subsequence)的更多相关文章
- [Algorithms] Using Dynamic Programming to Solve longest common subsequence problem
Let's say we have two strings: str1 = 'ACDEB' str2 = 'AEBC' We need to find the longest common subse ...
- Dynamic Programming | Set 3 (Longest Increasing Subsequence)
在 Dynamic Programming | Set 1 (Overlapping Subproblems Property) 和 Dynamic Programming | Set 2 (Opti ...
- 动态规划求最长公共子序列(Longest Common Subsequence, LCS)
1. 问题描述 子串应该比较好理解,至于什么是子序列,这里给出一个例子:有两个母串 cnblogs belong 比如序列bo, bg, lg在母串cnblogs与belong中都出现过并且出现顺序与 ...
- [Algorithms] Longest Common Subsequence
The Longest Common Subsequence (LCS) problem is as follows: Given two sequences s and t, find the le ...
- 1143. Longest Common Subsequence
link to problem Description: Given two strings text1 and text2, return the length of their longest c ...
- 最长公共字串算法, 文本比较算法, longest common subsequence(LCS) algorithm
''' merge two configure files, basic file is aFile insert the added content of bFile compare to aFil ...
- LintCode Longest Common Subsequence
原题链接在这里:http://www.lintcode.com/en/problem/longest-common-subsequence/ 题目: Given two strings, find t ...
- [UCSD白板题] Longest Common Subsequence of Three Sequences
Problem Introduction In this problem, your goal is to compute the length of a longest common subsequ ...
- LCS(Longest Common Subsequence 最长公共子序列)
最长公共子序列 英文缩写为LCS(Longest Common Subsequence).其定义是,一个序列 S ,如果分别是两个或多个已知序列的子序列,且是所有符合此条件序列中最长的,则 S 称为已 ...
随机推荐
- matlab-可视化图像阈值选择GUI工具
话不多说,先看图,这是导入一张图后运行的效果. 在此函数中,左图是灰度图加上colorBar后的彩色效果图,右图是二值化后的图,下面是可调节阈值的灰度直方图. 左上角的按钮是回归初始状态,右上角的按钮 ...
- 关于php查询mongodb限制返回字段的问题
最近想做一个前端控制接口字段返回的一个基础方法,通过mongodb 的find($query,$field)查询来规定查询的字段,但是遇到这么一个问题: 工作代码中有两个封装方法 : /** * 查询 ...
- 一直觉得用java很不顺心
一直觉得用java很不顺心,今儿想明白一个事情.如果把汇编比作石器时代,c作为冷兵器时代,c++作为工业革命之后的热兵器及机械化时代,而c#之类则进入了现代科学世界,至于go,python之流,大概可 ...
- node起一个简单服务,打开本地项目或文件浏览
1.安装nodejs 2.在项目文件夹目录下创建一个js文件,命名server.js(自定义名称),内容如下 var http = require('http'); var fs = require( ...
- 【原】The Linux Command Line - Workiing with commands
● type – Indicate how a command name is interpreted● which – Display which executable program will b ...
- 利用CSS3实现透明边框和多重边框
使用background-clip属性实现透明边框 .bordertest { border: 30px solid hsla(0,0%,90%,.5); background: #bbb; back ...
- python 安装包制作
1. __init__.py 2.模块1 模块2 3.setup.py from distutils.core import setup setup(name='modules_name',versi ...
- protobuf shutdownprotobuflibrary的时候crash,释放的指针出错
往往是多个子项目中有多次链接使用. 解决方法: 1. 使用静态库. 2. issure中有说2.6.1还未允许多次释放,建议使用3.4.x版本. 参考: https://github.com/prot ...
- [leetcode]65. Valid Number 有效数值
Validate if a given string can be interpreted as a decimal number. Some examples:"0" => ...
- [leetcode]33. Search in Rotated Sorted Array旋转过有序数组里找目标值
Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e. ...