Skip to content

Commit 9cbcd25

Browse files
committed
explanation added for 21 DP
1 parent 162f673 commit 9cbcd25

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,7 @@ it down into a story and later generalize to form recursive equations
385385
- [Find the number of n-bit integers which do not have any two consequent zeroes](/dynamic-programming/question18.c)
386386
- [Given a sentence without spaces between words. Break the words in such a way that they are meaningful](/dynamic-programming/question19.c)
387387
- [Partition problem](/dynamic-programming/question20.c)
388+
- [Find the longest palindromic subsequence](/dynamic-programming/question21.c)
388389

389390
## Some important concepts to solve algos better
390391

dynamic-programming/question21.c

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
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

Comments
 (0)