c++ - 打印最长公共(public)子序列

标签 c++ algorithm

我在最长子序列中面临的问题: 例如:

“ABCDGH” and “AEDFHR” is “ADH” of length 3

代码:

void lcs( char *X, char *Y, int m, int n )
{
   int L[m+1][n+1];

   /* Following steps build L[m+1][n+1] in bottom up fashion. Note
      that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1] */
   for (int i=0; i<=m; i++)
   {
     for (int j=0; j<=n; j++)
     {
       if (i == 0 || j == 0)
         L[i][j] = 0;
       else if (X[i-1] == Y[j-1])
         L[i][j] = L[i-1][j-1] + 1;
       else
         L[i][j] = max(L[i-1][j], L[i][j-1]);
     }
   }

我不明白为什么这行代码:

L[i][j] = max(L[i-1][j], L[i][j-1]);

如果我想打印序列,即 ADH 我该怎么做?

最佳答案

I don't understand why this line of code:

L[i][j] = max(L[i-1][j], L[i][j-1]);

如果 X[0..i-1] 的最后一个字符与 Y[0..j-1] 的最后一个字符不匹配,那么对于每个公共(public)子序列,至少有一个不属于这些字符。因此,答案由 X[0..i-2] 的最大长度给出。和Y[0..j-1] ,或 X[0..i-1] 的最大长度和Y[0..j-2] .

为了恢复实际的子序列,我们必须像这样追溯这些决策。

char lcs[min(m, n) + 1];
char *end = lcs;
int i = m;
int j = n;
while (i > 0 && j > 0) {
    if (X[i - 1] == Y[j - 1]) {
        *end = X[i - 1];
        end++;
        i--;
        j--;
    } else if (L[i - 1][j] >= L[i][j - 1]) {
        i--;
    } else {
        j--;
    }
}
reverse(lcs, end);
*end = '\0';
puts(lcs);

关于c++ - 打印最长公共(public)子序列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26325983/

相关文章:

C++ 为什么 const LPSTR 与 const char * 不同?

c++ - 将文件内容存储到C++中的变量中

algorithm - 找到最低票价

c# - C#中的滑动窗口算法

algorithm - Codility 的卡特彼勒方法的实际名称是什么?

algorithm - 从 Atm 减少到 A(我选择),然后从 A 减少到 Atm

c++ - 错误 C2440 : 'return' : cannot convert from 'int [2]' to 'int (&&)[2]'

c++ - 奇怪的 boolean 值

c++ - Swig 无法将 python3 的字节对象转换为 std::string

arrays - 证明这样的算法不存在