首先来看什么是最长公共子序列:给定两个序列,找到两个序列中均存在的最长公共子序列的长度。子序列需要以相关的顺序呈现,但不必连续。例如,“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)的更多相关文章

  1. [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 ...

  2. Dynamic Programming | Set 3 (Longest Increasing Subsequence)

    在 Dynamic Programming | Set 1 (Overlapping Subproblems Property) 和 Dynamic Programming | Set 2 (Opti ...

  3. 动态规划求最长公共子序列(Longest Common Subsequence, LCS)

    1. 问题描述 子串应该比较好理解,至于什么是子序列,这里给出一个例子:有两个母串 cnblogs belong 比如序列bo, bg, lg在母串cnblogs与belong中都出现过并且出现顺序与 ...

  4. [Algorithms] Longest Common Subsequence

    The Longest Common Subsequence (LCS) problem is as follows: Given two sequences s and t, find the le ...

  5. 1143. Longest Common Subsequence

    link to problem Description: Given two strings text1 and text2, return the length of their longest c ...

  6. 最长公共字串算法, 文本比较算法, longest common subsequence(LCS) algorithm

    ''' merge two configure files, basic file is aFile insert the added content of bFile compare to aFil ...

  7. LintCode Longest Common Subsequence

    原题链接在这里:http://www.lintcode.com/en/problem/longest-common-subsequence/ 题目: Given two strings, find t ...

  8. [UCSD白板题] Longest Common Subsequence of Three Sequences

    Problem Introduction In this problem, your goal is to compute the length of a longest common subsequ ...

  9. LCS(Longest Common Subsequence 最长公共子序列)

    最长公共子序列 英文缩写为LCS(Longest Common Subsequence).其定义是,一个序列 S ,如果分别是两个或多个已知序列的子序列,且是所有符合此条件序列中最长的,则 S 称为已 ...

随机推荐

  1. python3 json.dump乱码问题

    json.dumps(obj, ensure_ascii=False) ensure_ascii = True,会忽略掉non-ascii字符

  2. Java -- XStreamAlias 处理节点中的属性和值

    XStreamAlias 可以把objec和xml相互转换,但是有时候节点带有属性和值就需要特殊处理下: <?xml version="1.0" encoding=" ...

  3. Tools:apache部署https服务

    转自:https://www.cnblogs.com/ccccwork/p/6529367.html 1.要搭建https,必须要具备的东西 1.超文本传输协议httpd(apache)和ssl模块( ...

  4. PHP 设计模式(一)

    基础的三种设计模式 工厂模式 为创建对象提供了一个统一的接口,好处是当被创建对象命名空间或者名称改变时,直接修改工厂的创建方法即可 <?php class Factory{ public sta ...

  5. Java执行shell遇到的各种问题

    1.判断子进程是否执行结束 有的时候我们用java调用shell之后,之后的操作要在Process子进程正常执行结束的情况下才可以继续,所以我们需要判断Process进程什么时候终止. Process ...

  6. MM-实际应用中的难题

    SAP系统实际应用中的十大难题——塞依SAP培训 难题1:采购料维修 如果有物料坏了,需要退回给供应商处维修,此时一般不做退货.因为,第一,供应商不一定会乐意:第二,往来单据也无谓地增多:第三,最重要 ...

  7. 为docker私有registry配置nginx反向代理

    公司的Docker私有registry已经搭建好了,用官方的registry image很容易就搭建好了.现在就是要用nginx的反向代理把它放出来,以便在外网可以访问. 我的上一篇blog 讲了如何 ...

  8. int和string之间的转换

    #include<cstring> #include<algorithm> #include<stdio.h> #include<iostream> # ...

  9. Process 开启子进程 的两种方式、join控制子进程、守护进程

    一.join控制子进程的一种方式 当主进程需要在子进程结束之后结束时,我们需要用到join来控制子进程. import time import random from multiprocessing ...

  10. 在windows下安装Git并用GitHub同步

    准备环境: 1,注册github账户 2,下载安装git(下载地址:https://git-scm.com/download/win) 注释: git是什么? git是版本管理工具,当然也是分布式的管 ...