Dynamic Programming21 sections · 916 units
Open in Course

LeetCode 1143 Longest Common Subsequence - Transition

Match or skip

At position (i,j)(i, j), compare A[i-1] and B[j-1]. If they match: dp[i][j]=dp[i1][j1]+1dp[i][j] = dp[i-1][j-1] + 1. Found a common character, extend by 1. If they don't match: dp[i][j]=max(dp[i1][j],dp[i][j1])dp[i][j] = \max(dp[i-1][j], dp[i][j-1]). Skip a character from A or B, keep the better result. The final answer is dp[m][n]dp[m][n] where mm and nn are the lengths.

This formula tells you how to compute dp[i][j] from earlier dp values. Getting this right is the core of DP (dynamic programming).