1143. Longest Common Subsequence

Refer to labulado's one:

https://github.com/jiajunhua/labuladong-fucking-algorithm/blob/master/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92%E7%B3%BB%E5%88%97/%E6%9C%80%E9%95%BF%E5%85%AC%E5%85%B1%E5%AD%90%E5%BA%8F%E5%88%97.md

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?