1
+ /*
2
+ Find the longest palindromic subsequence
3
+
4
+ Naive approach:
5
+ Find all the subsequences of a given string. 2^n.
6
+ Then O(n) time to see if its a palindrome or not and then keep a variable to find the max
7
+ length. This time complexity is exponential
8
+
9
+ METHOD1:
10
+ DP: We can reverse the string and store it in an another string.
11
+ Now we can apply the algo to find the LCS. Whatever the LCS will be is going to be a palindrome
12
+ itself.
13
+
14
+ Time complexity: O(n^2)
15
+
16
+ METHOD:
17
+ DP: Explanation:
18
+ Here we can consider a string and try to match the first and the last element, like we do in order
19
+ to identify whether a string is a palindrome or not.
20
+ We will have two possibilities
21
+
22
+ if it matches (then we move the pointer ahead to compare the inner elements from both sides)
23
+ if it does not match (then we take max of two cases. In one we move pointer from right and keep left fixed
24
+ and other is opposite of it)
25
+
26
+ Recursive equation for the same can be formed as below:
27
+
28
+ PL(0,n-1) = {
29
+
30
+ PL(1,n-2) //if equal
31
+ max{ PL(0,n-2) , PL(1,n-1) } //if not equal
32
+ }
33
+
34
+ Now it is proved that it can be solved recursively. Now taking an example for 0,5 and making a tree
35
+ using these recursive equations will show us repeating sub problems.
36
+
37
+ Therefore, we need to find unique sub problems, for that we generalize the definition of recursive eqns
38
+ as:
39
+ PL (i, j)
40
+ if 1 n-1 //if value of i is 1 j can be between 1 and n-1, therefore it can have n-1 values
41
+ 2 n-2
42
+ 3 n-3 and so on
43
+
44
+ That means there are n^2 unique sub problems
45
+
46
+ Therefore, we make a matrix of size n^2 and ...
47
+
48
+ */
0 commit comments