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?
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 :
L[i-1,j]
;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).