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.mdarrow-up-right

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