动态规划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"); }
相关文章推荐
- jQuery 判断图片是否加载完成方法汇总
- ORA-00845: MEMORY_TARGET not supported on this system报错解决
- hdu1198
- 计蒜客 难题题库 135 数字加1
- hdu 1233 还是畅通工程【最小生成树】
- ubuntu 14.04安装xen
- hdu5355--Cake(构造)
- DevExpress v15.1:ASP.NET WebForms功能增强(一)
- 计蒜客 难题题库 134 求出现次数最多的字符
- 网站静态化(转)
- HQL select总结
- strlen函数,strcat函数,strcpy函数,strncpy函数,strcmp函数实现
- 剖析 Linux hypervisor
- 华为机试题二
- Mysql初始化root密码和允许远程访问
- Leetcode解题笔记-Pascal's Triangle II
- iOS开发——汉字转拼音
- 基于jQuery弹出层的9种效果
- 计蒜客 难题题库 133 冒泡排序
- 华为机试题