Longest Common Subsequence for Multiple Sequences

前端 未结 3 1866
旧巷少年郎
旧巷少年郎 2020-12-14 10:49

I have done a bunch of research for finding the longest for M = 2 sequences, but I am trying to figure out how to do it for M ≥ 2 sequences

I am being given N and M:

3条回答
  •  情深已故
    2020-12-14 11:36

    Since you have unique elements, @Nikita Rybak's answer is the one to go with, but since you mentioned dynamic programming, here's how you'd use DP when you have more than two sequences:

    dp[i, j, k] = length of longest common subsequence considering the prefixes
                  a[1..i], b[1..j], c[1..k].
    
    
    dp[i, j, k] = 1 + dp[i - 1, j - 1, k - 1] if a[i] = b[j] = c[k]
                = max(dp[i - 1, j, k], dp[i, j - 1, k], dp[i, j, k - 1]) otherwise
    

    To get the actual subsequence back, use a recursive function that starts from dp[a.Length, b.Length, c.Length] and basically reverses the above formulas: if the three elements are equal, backtrack to dp[a.Length - 1, b.Length - 1, c.Length - 1] and print the character. If not, backtrack according to the max of the above values.

提交回复
热议问题