1143. Longest Common Subsequence


Refer to labulado's one:
DFS
關鍵 ->
lcs 當有相同的字時, dp(i-1,j-1) + 1
不相同時 可能是 max(dp(i-1, j), dp(i, j-1), dp(i-1, j-1)), 因為取最大 所以 dp(i-1, j-1) 效果不好 可以忽略
一路從尾巴 倒推回頭(-1 是終止條件)
Memo + DFS
DFS+memo, from 0, 0
所以 dp table 存的就會是
the length of longest common subsequence of A[i] and B[j]
time: O(mn)
space: O(mn)
new way
if we add in string , more "" in the front, the index become normal i, j

compressed to 1d
buttom up
Last updated
Was this helpful?