buGMaster's blog

By buGMaster, 11 years ago, In English

I've used this recursive relation to solve this classic problem. Here it is:

if (I == n || J == m)
        dp[I][J] = 0;
else if (x[I] == y[J])
        dp[I][J] = dp[I+1][J+1] + 1;
else
        dp[I][J] = max (dp[I+1][J], dp[I][J+1]);

but I've seen the USACO TEXT about Dynamic Programming, that it used this pseudocode for this problem:

   # the tail of the second sequence is empty
 1   for element = 1 to length1
 2     length[element, length2+1] = 0

    # the tail of the first sequence has one element
 3   matchelem = 0
 4   for element = length2 to 1
 5     if list1[length1] = list2[element]
 6       matchelem = 1
 7     length[length1,element] = nmatchlen

    # loop over the beginning of the tail of the first sequence
 8   for loc = length1-1 to 1
 9     maxlen = 0
10     for element = length2 to 1

    # longest common subsequence doesn't include first element
11       if length[loc+1,element] > maxlen
12         maxlen = length[loc+1,element]

    # longest common subsequence includes first element
13       if list1[loc] = list2[element] &&
14                       length[loc+1,element+1]+1 > maxlen
15           maxlen = length[loc,element+1] + 1

16     length[loc,element] = maxlen

It it a bit different with my solution. Instead of dp[I][J] = max (dp[I+1][J], dp[I][J+1]); , it's used below code.

    # longest common subsequence doesn't include first element
11       if length[loc+1,element] > maxlen
12         maxlen = length[loc+1,element]

Why this solution just checks length[loc+1,element] and doesn't check length[loc,element+1]? Does this solution guarantee to find the correct answer?

Please guide me to get this point! Thanks for you help...

  • Vote: I like it
  • +4
  • Vote: I do not like it