next up previous
Next: Up: Previous:

Distinct Subproblems

Could write an exponential recursive algorithm, but there are only m*n distinct subproblems.



Solution

Let c[i,j] be maximum length array.

Let b[i,j] record the case relating Xi, Yj, and Zk.



LCSLength(x, y)                       j <---
   m = length(x)                   +------------
   n = length(y)                   | \
   for i = 1 to m                i |  \
      c[i,0] = 0                 ^ |   \
   for j = 0 to n                | |
      c[0,j] = 0                 | |
   for i = 1 to m                | |
      for j = 1 to n               |
         if x[i] = y[j]
         then c[i,j] = c[i-1,j-1] + 1
              b[i,j] = '\'             ; Arrow points up and left
         else if c[i-1,j] >= c[i,j-1]
              then c[i,j] = c[i-1,j]
                 b[i,j] = '^'          ; Up arrow
              else c[i,j] = c[i,j-1]
                 b[i,j] = '<'          ; Left arrow
   return c and b



LCSLength is O(mn).


next up previous
Next: Up: Previous: