LCS,最长公共子序列

思路比较简单就是逐个比较,为了避免重复计算,我们将记录每次计算的值。

int main(void)
{
    char s[] = "ATCJKDLB";
    char exp[] = "CKLBG";

    int m = strlen(s);
    int n = strlen(exp);
    int L[m+1][n+1];
    int i,j;
    for(i = 0; i <= m; i++)
    {
        for(j = 0; j <= n; j++)
        {
            if(j ==0 || i ==0)
                L[i][j] = 0;
            else if(s[i-1] == exp[j-1])
                L[i][j] = L[i-1][j-1] +1;
            else
                L[i][j] = max(L[i-1][j],L[i][j-1]);
        }
    }

    cout << L[m][n] << endl;
    return 0;
}

 

点赞