您的位置:首页 > 其它

动态规划1——最长公共子序列

2015-08-10 09:50 148 查看

最长公共子串(Longest Common Substring)最长公共子序列(Longest Common Subsequence)的区别: 子串要求在原字符串中是连续的,而子序列则只需保持相对顺序,并不要求连续。


问题描述:给定两个序列:
X[1...m]
Y[1...n]
,求在两个序列中同时出现的最长子序列的长度。

动态规划

首先,我们来看看 LCS 问题是否具有动态规划问题的两个特性。

① 最优子结构

C[i,j] = |LCS(x[1...i],y[1...j])|
,即
C[i,j]
表示序列
X[1...i]
Y[1...j]
的最长公共子序列的长度,则
C[m,n = |LCS(x,y)|
就是问题的解。

递归推导式:



在这里就不证明了。从这个递归公式可以看出,问题具有最优子结构性质!

#include<iostream>
#include<vector>
#include<string>
#include<math.h>
using namespace std;

int LCS(string &str1,string &str2)
{
if(str1.empty()||str2.empty())
return 0;
int len1=str1.size();
int len2=str2.size();

int **temp=new int*[len1];
for(int i=0;i<len1;i++)
temp[i]=new int[len2];
for(int i=0;i<len1;i++)
for(int j=0;j<len2;j++)
temp[i][j]=0;

for(int j=0;j<len2;j++)
{
if(str1[0]==str2[j])
temp[0][j]=1;
else
{
if(j==0)
temp[0][j]=0;
else
temp[0][j]=temp[0][j-1];
}
}

for(int i=0;i<len2;i++)
{
if(str1[i]==str2[0])
temp[i][0]=1;
else
{
if(i==0)
temp[i][0]=0;
else
temp[i][0]=temp[i-1][0];
}
}

for(int i=1;i<len1;i++)
for(int j=1;j<len2;j++)
{
if(str1[i]==str2[j])
temp[i][j]=temp[i-1][j-1]+1;
else
temp[i][j]=max(temp[i][j-1],temp[i-1][j]);
}
int re=temp[len1-1][len2-1];

for(int i=0;i<len1;i++)
delete []temp[i];
delete []temp;
temp=NULL;

return re;
}

int main()
{
string str1="ABCBDAB";
string str2="BDCABA";
int len;
len=LCS(str1,str2);
cout<<len<<endl;
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: