1

The recurrence for lcs is:

L[i,j] = max(L[i-1,j], L[i,j-1]) if a[i] != a[j]

Can you tell me why it is i-1 or j-1? Why isn't L[i,j] = L[i-1,j-1] correct?

reto
  • 9,995
  • 5
  • 53
  • 52
ffff
  • 2,853
  • 1
  • 25
  • 44

1 Answers1

0

You are considering the case where a[i] != a[j], which means that the letters you are currently comparing of the two sequences A and B are different. Therefore, the length of the longest common subsequence is one of two things :

  1. the longest common subsequence of the current substring of A minus its first character and B, i.e. L[i-1,j] ;
  2. the longest common subsequence of A and the current substring of B minus its first character, i.e. L[i,j-1].

If L[i-1,j-1] were correct, it would mean that the current characters in both A and B do not count, they don’t get a "chance" to be part of the subsequence.

See for example this explanation (note that it works forward in the sequences instead of backward).

Zoyd
  • 3,449
  • 1
  • 18
  • 27