Dynamic Programming21 sections · 915 units
Open in Course

LeetCode 516 Longest Palindromic Subsequence - Transition

Match or skip

The recurrence has two cases based on whether the endpoints match. If s[i]=s[j]s[i] = s[j]: Both characters can extend a palindrome. Look at dp[i+1][j−1]dp[i+1][j-1] (the inner substring) and add 22.

So dp[i][j]=dp[i+1][j−1]+2dp[i][j] = dp[i+1][j-1] + 2. If s[i]≠s[j]s[i] \neq s[j]: At least one endpoint isn't part of the LPS. Take the better of excluding s[i]s[i] or excluding s[j]s[j]: dp[i][j]=max⁡(dp[i+1][j],dp[i][j−1])dp[i][j] = \max(dp[i+1][j], dp[i][j-1]). Notice the dependency: dp[i][j]dp[i][j] needs dp[i+1][...]dp[i+1][...] and dp[...][j−1]dp[...][j-1]. These are shorter ranges. Iterate by increasing interval length so subproblems are ready.