最长公共子序列-动态规划



代码:递归
#include <iostream> #include <cstring> #include <algorithm> using namespace std; char str1[10]; char str2[10]; int maxLen(char str1[],char str2[],int i,int j) { if(i==0||j==0) return 0; if(str1[i-1]==str2[j-1]) { return maxLen(str1,str2,i-1,j-1)+1; }else { return max(maxLen(str1,str2,i-1,j),maxLen(str1,str2,i,j-1)); } } int main(){ cin>>str1; cin>>str2; int i; int j; i=strlen(str1); j=strlen(str2); cout<<maxLen(str1,str2,i,j); return 0; }
代码:不递归,用二维数组表示状态
#include <iostream> #include <cmath> #include <algorithm> #include <cstring> using namespace std; char str1[10]; char str2[10]; int MaxLen[10][10]; int main(){ while(cin>>str1>>str2){ int len1=strlen(str1); int len2=strlen(str2); int i,j; for(i=0;i<len1;i++){ MaxLen[i][0]=0; } for(j=0;j<len2;j++){ MaxLen[0][j]=0; } for(i=1;i<=len1;i++) { for(j=1;j<=len2;j++) { if(str1[i-1]==str2[j-1]) MaxLen[i][j]=MaxLen[i-1][j-1]+1; else{ MaxLen[i][j]=max(MaxLen[i-1][j],MaxLen[i][j-1]); }} } cout<<MaxLen[len1][len2]<<endl; } }
本文来自博客园,作者:坤k,转载请注明原文链接:https://www.cnblogs.com/fukunwang/p/15716848.html

浙公网安备 33010602011771号