---
title: "（转载）动态规划求最长公共子序列"
author: "xdgj"
date: "2011-04-21T11:32:41Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2011-04-21T11:51:58Z"
id: 1010929
url: "https://xdgj.iteye.com/blog/1010929"
---

通过这篇来加深对动态规划的理解。

 **动态规划法**

经常会遇到复杂问题不能简单地分解成几个子问题，而会分解出一系列的子问题。简单地采用把大问题分解成子问题，并综合子问题的解导出大问题的解的方法，问题求解耗时会按问题规模呈幂级数增加。

为了节约重复求相同子问题的时间，引入一个数组，不管它们是否对最终解有用，把所有子问题的解存于该数组中，这就是动态规划法所采用的基本方法。

 

 

【问题】 求两字符序列的最长公共字符子序列

问题描述：字符序列的子序列是指从给定字符序列中随意地（不一定连续）去掉若干个字符（可能一个也不去掉）后所形成的字符序列。令给定的字符序列X=“x0，x1，…，xm-1”，序列Y=“y0，y1，…，yk-1”是X的子序列，存在X的一个严格递增下标序列&lt;i0，i1，…，ik-1&gt;，使得对所有的j=0，1，…，k-1，有xij=yj。例如，X=“ABCBDAB”，Y=“BCDB”是X的一个子序列。

考虑最长公共子序列问题如何分解成子问题，设A=“a0，a1，…，am-1”，B=“b0，b1，…，bn-1”，并Z=“z0，z1，…，zk-1”为它们的最长公共子序列。不难证明有以下性质：

（1） 如果am-1=bn-1，则zk-1=am-1=bn-1，且“z0，z1，…，zk-2”是“a0，a1，…，am-2”和“b0，b1，…，bn-2”的一个最长公共子序列；

（2） 如果am-1!=bn-1，则若zk-1!=am-1，蕴涵“z0，z1，…，zk-1”是“a0，a1，…，am-2”和“b0，b1，…，bn-1”的一个最长公共子序列；

（3） 如果am-1!=bn-1，则若zk-1!=bn-1，蕴涵“z0，z1，…，zk-1”是“a0，a1，…，am-1”和“b0，b1，…，bn-2”的一个最长公共子序列。

这样，在找A和B的公共子序列时，如有am-1=bn-1，则进一步解决一个子问题，找“a0，a1，…，am-2”和“b0，b1，…，bm-2”的一个最长公共子序列；如果am-1!=bn-1，则要解决两个子问题，找出“a0，a1，…，am-2”和“b0，b1，…，bn-1”的一个最长公共子序列和找出“a0，a1，…，am-1”和“b0，b1，…，bn-2”的一个最长公共子序列，再取两者中较长者作为A和B的最长公共子序列。

求解：

 

引进一个二维数组c\[]\[]，用c\[i]\[j]记录X\[i]与Y\[j] 的LCS 的长度，b\[i]\[j]记录c\[i]\[j]是通过哪一个子问题的值求得的，以决定搜索的方向。  
我们是自底向上进行递推计算，那么在计算c\[i,j]之前，c\[i-1]\[j-1]，c\[i-1]\[j]与c\[i]\[j-1]均已计算出来。此时我们根据X\[i] = Y\[j]还是X\[i] != Y\[j]，就可以计算出c\[i]\[j]。

问题的递归式写成：

 

![recursive formula](http://p.blog.csdn.net/images/p_blog_csdn_net/hhygcy/EntryImages/20090302/lcs_1.PNG)

回溯输出最长公共子序列过程：

![flow](http://p.blog.csdn.net/images/p_blog_csdn_net/hhygcy/EntryImages/20090302/lcs_2.PNG)

算法分析：  
由于每次调用至少向上或向左（或向上向左同时）移动一步，故最多调用(m + n)次就会遇到i = 0或j = 0的情况，此时开始返回。返回时与递归调用时方向相反，步数相同，故算法时间复杂度为Θ(m + n)。

代码：

![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)#include &lt;stdio.h&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)#include &lt;string.h&gt;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)#define MAXLEN 100  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)void LCSLength(char \*x, char \*y, int m, int n, int c\[]\[MAXLEN], int b\[]\[MAXLEN])  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif){  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    int i, j;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)      
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    for(i = 0; i &lt;= m; i++)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        c\[i]\[0] = 0;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    for(j = 1; j &lt;= n; j++)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        c\[0]\[j] = 0;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    for(i = 1; i&lt;= m; i++)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)    {  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        for(j = 1; j &lt;= n; j++)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)        {  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            if(x\[i-1] == y\[j-1])  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)            {  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                c\[i]\[j] = c\[i-1]\[j-1] + 1;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                b\[i]\[j] = 0;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)            }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            else if(c\[i-1]\[j] &gt;= c\[i]\[j-1])  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)            {  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                c\[i]\[j] = c\[i-1]\[j];  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                b\[i]\[j] = 1;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)            }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)            else  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)            {  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                c\[i]\[j] = c\[i]\[j-1];  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)                b\[i]\[j] = -1;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)            }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)        }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)}  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)void PrintLCS(int b\[]\[MAXLEN], char \*x, int i, int j)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif){  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    if(i == 0 || j == 0)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        return;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    if(b\[i]\[j] == 0)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)    {  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        PrintLCS(b, x, i-1, j-1);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        printf("%c ", x\[i-1]);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockEnd.gif)    }  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    else if(b\[i]\[j] == 1)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        PrintLCS(b, x, i-1, j);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    else  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)        PrintLCS(b, x, i, j-1);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)}  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/None.gif)int main(int argc, char \*\*argv)  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockStart.gif){  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)    char x\[MAXLEN] = {"ABCBDAB"};  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedSubBlockStart.gif)    char y\[MAXLEN] = {"BDCABA"};  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    int b\[MAXLEN]\[MAXLEN];  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    int c\[MAXLEN]\[MAXLEN];  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    int m, n;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)      
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    m = strlen(x);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    n = strlen(y);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)      
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    LCSLength(x, y, m, n, c, b);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    PrintLCS(b, x, m, n);  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)      
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/InBlock.gif)    return 0;  
![](http://images.csdn.net/syntaxhighlighting/OutliningIndicators/ExpandedBlockEnd.gif)}

 

转载自：[http://blog.csdn.net/yysdsyl/archive/2009/05/30/4226630.aspx](http://blog.csdn.net/yysdsyl/archive/2009/05/30/4226630.aspx)