You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: dynamic_programming/StrategiesForSubsequenceProblem.md
+6-6Lines changed: 6 additions & 6 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -73,7 +73,7 @@ Now let's talk about the Longest Palindrome Subsequence (LPS) problem to explain
73
73
74
74
We have solve the "Longest Palindrome Substring" problem before. This time, the difficulty is increased by finding the length of the Longest Palindrome Subsequence instead of substring:
75
75
76
-

76
+

77
77
78
78
In this question, **we define `dp[i][j]` as the length of the longest palindrome subsequence within the substring `s[i..j]`**. Please remember this definition so as to understand the algorithm.
79
79
@@ -83,19 +83,19 @@ Specifically, if we want to find `dp[i][j]`, suppose you have already got the re
83
83
84
84
85
85
86
-

86
+

87
87
88
88
The answer is yes! It depends on the characters of `s[i]` and `s[j]`:
89
89
90
90
**If they are equal**, then the longest palindrome subsequence in `s[i+1..j-1]` would be these two characters plus the longest palindrome subsequence in `s[i..j]`:
91
91
92
92
93
93
94
-

94
+

95
95
96
96
**If they are not equal**, it means that they **cannot appear at the same time** in the longest palindrome subsequence of `s[i..j]`. Therefore, we add them **separately** to `s[i+1..j-1] ` to see which substring produces a longer palindrome subsequence:
97
97
98
-

98
+

99
99
100
100
The code of the above two cases can be written like this:
101
101
@@ -118,9 +118,9 @@ Since `i`must be less than or equal to `j`, for those locations where `i > j`, t
118
118
119
119
In addition, look at the state transition equation we just got. To find `dp[i][j]`, you need to know `dp[i+1][j-1]`, `dp[i+1][j]` and`dp[i][j -1]` these three values. And look at the base case we determined, this is how the DP array looks like after being filled:
120
120
121
-

121
+

122
122
123
-
**In order to guarantee that before each calculation of `dp[i][j]`, the values in the left, down and right direction have been calculated, we can only traverse it diagonally or reversely**:
123
+
**In order to guarantee that before each calculation of `dp[i][j]`, the values in the left, down and right direction have been calculated, we can only traverse it diagonally or reversely**:
124
124
125
125
Here I choose to traverse reversely. The code is as follows:
0 commit comments