PrintLCS(b, X, i, j) if i=0 or j=0 then return if b[i,j] = '\' then PrintLCS(b, X, i-1, j-1) print x[i] else if b[i,j] = '^' then PrintLCS(b, X, i-1, j) else PrintLCS(b, X, i, j-1)
PrintLCS is O(m+n).
0 1 2 3 4 5 y[j] b r o w n +---+---+---+---+---+---+ PrintLCS(b, "cow", 3, 5) < 0 x[i] | 0 | 0 | 0 | 0 | 0 | 0 | PrintLCS(b, "cow", 3, 4) \ +---+---+---+---+---+---+ PrintLCS(b, "cow", 2, 3) \ 1 c | 0 | 0 | 0 | 0 | 0 | 0 | PrintLCS(b, "cow", 1, 2) 0 +---+---+---+---+---+---+ 2 o | 0 | 0 | 0 |\1 |<1 |<1 | o w +---+---+---+---+---+---+ 3 w | 0 | 0 | 0 |^1 |\2 |<2 | +---+---+---+---+---+---+
LCS Demo