Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 1143 Longest Common Subsequence - Walkthrough

Tracing the algorithm

Trace LCS on s1="ABCBDAB"s_1 = \text{"ABCBDAB"} and s2="BDCAB"s_2 = \text{"BDCAB"}. Build the DP table. dp[i][j]dp[i][j] = LCS length of s1[0..i1]s_1[0..i-1] and s2[0..j1]s_2[0..j-1].

When characters match (s1[i1]=s2[j1]s_1[i-1] = s_2[j-1]): dp[i][j]=dp[i1][j1]+1dp[i][j] = dp[i-1][j-1] + 1. Otherwise: dp[i][j]=max(dp[i1][j],dp[i][j1])dp[i][j] = \max(dp[i-1][j], dp[i][j-1]). Final answer: dp[7][5]=4dp[7][5] = 4. The LCS is "BDAB" or "BCAB". Trace back from dp[7][5]dp[7][5] to reconstruct. Backtrack from the final cell to reconstruct the actual subsequence. Follow the arrows that gave the maximum.