算法:
递归法:对于序列A[0,n]]和B[0,m],LCS(A,B)无非三种情况
-
若A或B为空,则LCS为空,作为递归基
-
如果末字符相等,即A[n]=B[m]=‘X’,则取LCS(A[0,n),B[0,m))+‘X’,如果前者可以求解,则问题的规模被缩小
-
如果末字符不相等,即A[n]!=B[m],比如A[n]=a,B[m]=b,则a和b至多有一个会出现在最后的解里(对解有贡献)。因为比如a有贡献,那B在前[0,m)个字符里一定有a,之后A就结束了(a是A的最后一个字符),A中不可能再有b可以和B匹配。
当然可也能两者都不出现在最后的解里。
可以正向来做,最后把结果反过来
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
string longerString(string A,string B);
string LCS(string A,string B);
string furtherLCS(string A,string B);
int main(int argc, char const *argv[])
{
cout<<LCS("educational","advantage");
return 0;
}
string longerString(string A,string B)
{
if(A.size()>B.size())
return A;
else return B;
}
string LCS(string A,string B)
{