求最長公共子序列
例如:
對於一個長度爲n的序列,它一共有2^n 個子序列,有(2^n – 1)個非空子序列。
請注意:子序列不是子集,它和原始序列的元素順序是相關的。
(2)公共子序列 : 顧名思義,如果序列C既是序列A的子序列,同時也是序列B的子序列,則稱它爲序列A和序列B的公共子序列。
例如:
序列1,8,7是它們的一個公共子序列。
請注意: 空序列是任何兩個序列的公共子序列。
仍然用序列1,3,5,4,2,6,8,7和序列1,4,8,6,7,5
它們的最長公共子序列是:
1,4,8,7
1,4,6,7
請注意: 最長公共子序列不唯一。
求最長公共子序列
第1行:字符串A 第2行:字符串B (A,B的長度 <= 1000)
輸出最長的子序列,如果有多個,隨意輸出1個。
abcicba abdkscab
輸出示例
abca
#include<cstdio>
#include<cstring>
#include<string>
#include<stack>
#include<algorithm>
using namespace std;
char str1[1005],str2[1005];
int dp[1005][1005]={0};
int main()
{
int n,m,i,j;
while(scanf("%s %s",str1+1,str2+1)!=EOF)
{
str1[0]=str2[0]='0';
int l1=strlen(str1)-1;
int l2=strlen(str2)-1;
for(i = 1;i <= l1;i++)
{
for(j = 1;j <= l2;j++)
{
if(str1[i] == str2[j])
dp[i][j] = dp[i-1][j-1]+1;
else
dp[i][j] = max(dp[i-1][j],dp[i][j-1]);
}
}
// printf("%d\n",dp[l1][l2]);
//回溯求LCS
int pos1 = l1;
int pos2 = l2;
stack<char> S;
while (pos1 > 0 && pos2 > 0)
{
if (str1[pos1] == str2[pos2])
{
S.push(str1[pos1]);
pos1--;
pos2--;
}
else if (dp[pos1-1][pos2] > dp[pos1][pos2-1])
pos1--;
else
pos2--;
}
while (!S.empty())
{
printf ("%c",S.top());
S.pop();
}
printf("\n");
}
return 0;
}