Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 1143 Longest Common Subsequence - State Design

The 2D table

Define dp[i][j]dp[i][j] as the length of the LCS (Longest Common Subsequence) of the first ii characters of A and the first jj characters of B. Why this definition? At each step, you're either matching characters or skipping one.

You need to track progress in both strings independently. Base cases: dp[0][j]=0dp[0][j] = 0 for all jj (empty A has no common subsequence with anything). dp[i][0]=0dp[i][0] = 0 for all ii (empty B has no common subsequence with anything).