0

I've read the solutions to the LCS problem. But now there's a Longest Similar Subsequence problem: A sequence C is a similar subsequence of two sequences A, B if and only if C is a subsequence of A and we can replace at most K elements in C such that C is a subsequence of B.

For example, if A = "ABCDE", B = "BCAFE", K = 1, then the longest similar subsequence is "BCDE" ("BCDE is a subsequence of "ABCDE", and we can replace 'D' with 'A' or 'F' to make it a subsequence of "BCAFE").

My problem is that I've only come up with a recursive method to solve it, but obviously this is time-consuming, so I want to use DP instead. Any idea how to use DP to solve this problem?

My recursion method is like this:

LSS(i, j, k)
    if(i == 0 or j == 0)
        return 0
    if(A[i] == B[j])
        return LSS(i-1, j-1, k) + 1
    if(k > 0)
        return max(LSS(i-1, j-1, k-1) + 1, LSS(i-1, j, k), LSS(i, j-1, k))
    else
        return max(LSS(i-1, j, k), LSS(i, j-1, k))
Einsambr
  • 189
  • 2
  • 11

1 Answers1

1

DP is all about understanding the optimal sub-problem and then use it in getting other solution. Without all that details we can simply use the idea that comes automatically.

Here what we are doing is simply computing the same solution over and over. That's why the solution is much more time consuming. What you can do is memoize the solution.

So in this case intialize sol with -1. Then before getting the solution of LSS(i,j,k) you can check whether sol[i][j][k] is already computed. If it is then just use it otherwise solve the solution and put it in sol. Standarrd memoization.

user2736738
  • 30,591
  • 5
  • 42
  • 56
  • Thank you. But what I was wondering (I did not make it clear in the question) is there a way to transform it to a 2-dimension problem and use bottom-up DP to solve it? That is, get rid of k and make it pretty similar to a LCS problem? – Einsambr Oct 18 '17 at 07:13
  • @Einsambr.: Ah this I will have to check..I guess there is a way. – user2736738 Oct 18 '17 at 07:15