Sei sulla pagina 1di 4

6/10/2015

DynamicProgramming|Set12(LongestPalindromicSubsequence)GeeksforGeeks

DynamicProgramming|Set12
(LongestPalindromicSubsequence)
Givenasequence,findthelengthofthelongestpalindromicsubsequenceinit.
Forexample,ifthegivensequenceisBBABCBCAB,thentheoutputshould
be7asBABCBABisthelongestpalindromicsubseuqnceinit.BBBBBand
BBCBBarealsopalindromicsubsequencesofthegivensequence,butnot
thelongestones.
Thenaivesolutionforthisproblemistogenerateallsubsequencesofthegiven
sequenceandfindthelongestpalindromicsubsequence.Thissolutionis
exponentialintermoftimecomplexity.Letusseehowthisproblempossesses
bothimportantpropertiesofaDynamicProgramming(DP)Problemandcan
efficientlysolvedusingDynamicProgramming.
1)OptimalSubstructure:
LetX[0..n1]betheinputsequenceoflengthnandL(0,n1)bethelengthof
thelongestpalindromicsubsequenceofX[0..n1].
IflastandfirstcharactersofXaresame,thenL(0,n1)=L(1,n2)+2.
ElseL(0,n1)=MAX(L(1,n1),L(0,n2)).
Followingisageneralrecursivesolutionwithallcaseshandled.
//Everaysinglecharacterisapalindromoflength1
L(i,i)=1forallindexesiingivensequence
//IFfirstandlastcharactersarenotsame
If(X[i]!=X[j])L(i,j)=max{L(i+1,j),L(i,j1)}
//Ifthereareonly2charactersandbotharesame
Elseif(j==i+1)L(i,j)=2
//Iftherearemorethantwocharacters,andfirstandlast
//charactersaresame
ElseL(i,j)=L(i+1,j1)+2

2)OverlappingSubproblems
FollowingissimplerecursiveimplementationoftheLPSproblem.The
implementationsimplyfollowstherecursivestructurementionedabove.
#include<stdio.h>
#include<string.h>

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%

1/4

6/10/2015

DynamicProgramming|Set12(LongestPalindromicSubsequence)GeeksforGeeks

//Autilityfunctiontogetmaxoftwointegers
intmax(intx,inty){return(x>y)?x:y;}

//Returnsthelengthofthelongestpalindromicsubsequenceinseq
intlps(char*seq,inti,intj)
{
//BaseCase1:Ifthereisonly1character
if(i==j)
return1;

//BaseCase2:Ifthereareonly2charactersandbotharesame
if(seq[i]==seq[j]&&i+1==j)
return2;

//Ifthefirstandlastcharactersmatch
if(seq[i]==seq[j])
returnlps(seq,i+1,j1)+2;

//Ifthefirstandlastcharactersdonotmatch
returnmax(lps(seq,i,j1),lps(seq,i+1,j));
}

/*Driverprogramtotestabovefunctions*/
intmain()
{
charseq[]="GEEKSFORGEEKS";
intn=strlen(seq);
printf("ThelnegthoftheLPSis%d",lps(seq,0,n1));
getchar();
return0;
}
Output:
ThelnegthoftheLPSis5

Consideringtheaboveimplementation,followingisapartialrecursiontreefora
sequenceoflength6withalldifferentcharacters.
L(0,5)
/\
/\
L(1,5)L(0,4)
/\/\
/\/\
L(2,5)L(1,4)L(1,4)L(0,3)

Intheabovepartialrecursiontree,L(1,4)isbeingsolvedtwice.Ifwedrawthe
completerecursiontree,thenwecanseethattherearemanysubproblems
whicharesolvedagainandagain.Sincesamesuproblemsarecalledagain,
thisproblemhasOverlappingSubprolemsproperty.SoLPSproblemhasboth
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%

2/4

6/10/2015

DynamicProgramming|Set12(LongestPalindromicSubsequence)GeeksforGeeks

properties(seethisandthis)ofadynamicprogrammingproblem.Likeother
typicalDynamicProgramming(DP)problems,recomputationsofsame
subproblemscanbeavoidedbyconstructingatemporaryarrayL[][]inbottom
upmanner.
DynamicProgrammingSolution

#include<stdio.h>
#include<string.h>

//Autilityfunctiontogetmaxoftwointegers
intmax(intx,inty){return(x>y)?x:y;}

//Returnsthelengthofthelongestpalindromicsubsequenceinseq
intlps(char*str)
{
intn=strlen(str);
inti,j,cl;
intL[n][n];//Createatabletostoreresultsofsubproblems

//Stringsoflength1arepalindromeoflentgh1
for(i=0;i<n;i++)
L[i][i]=1;

//Buildthetable.Notethatthelowerdiagonalvaluesoftable
//uselessandnotfilledintheprocess.Thevaluesarefilledi
//mannersimilartoMatrixChainMultiplicationDPsolution(See
//http://www.geeksforgeeks.org/archives/15553).clislengthof
//substring
for(cl=2;cl<=n;cl++)
{
for(i=0;i<ncl+1;i++)
{
j=i+cl1;
if(str[i]==str[j]&&cl==2)
L[i][j]=2;
elseif(str[i]==str[j])
L[i][j]=L[i+1][j1]+2;
else
L[i][j]=max(L[i][j1],L[i+1][j]);
}
}

returnL[0][n1];
}

/*Driverprogramtotestabovefunctions*/
intmain()
{
charseq[]="GEEKSFORGEEKS";
intn=strlen(seq);
printf("ThelnegthoftheLPSis%d",lps(seq));
getchar();
data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%

3/4

6/10/2015

DynamicProgramming|Set12(LongestPalindromicSubsequence)GeeksforGeeks

return0;
}
Output:
ThelnegthoftheLPSis7

TimeComplexityoftheaboveimplementationisO(n^2)whichismuchbetter
thantheworstcasetimecomplexityofNaiveRecursiveimplementation.
ThisproblemisclosetotheLongestCommonSubsequence(LCS)problem.In
fact,wecanuseLCSasasubroutinetosolvethisproblem.Followingisthe
twostepsolutionthatusesLCS.
1)Reversethegivensequenceandstorethereverseinanotherarraysay
rev[0..n1]
2)LCSofthegivensequenceandrev[]willbethelongestpalindromic
sequence.
ThissolutionisalsoaO(n^2)solution.
Pleasewritecommentsifyoufindanythingincorrect,oryouwanttosharemore
informationaboutthetopicdiscussedabove.
References:
http://users.eecs.northwestern.edu/~dda902/336/hw6sol.pdf

data:text/htmlcharset=utf8,%3Cdiv%20class%3D%22posttitleinfo%22%20style%3D%22float%3A%20left%3B%20fontsize%3A%201.1em%3B%20width%

4/4

Potrebbero piacerti anche