Dynamic Programming is an efficient algorithm that is commonly used to solve optimization problems. In this case, a dynamic programming algorithm is designed to find the longest palindrome sequence.
the longest palindrome sequence : A palindrome is an empty string with the same sequence as the reverse order. For example, Civic,racecar itself is the longest palindrome sequence of its own. For example, the longest palindrome sequence of character is Carac.
Dynamic planning generally consists of four steps:
1, characterizing the structural characteristics of an optimal solution
2, recursively define the value of the optimal solution
3, calculate the value of the optimal solution
4, an optimal solution is constructed using the computed information.
The following four steps are followed to design a dynamic programming algorithm.
1, describing the structure of the optimal solution
The X "I,j" represents the given sequence, and F "I,j" represents the longest palindrome subsequence of X "I,j". The conclusion is established
(1) If the first and last elements of X are the same, then F "I,j" =f "I+1,j-1"
(2) If the first and last elements of X are not the same, then F "I,j" =max (f "i+1,j", F "i,j-1")
2, construct a land-return solution
F "I,j" =f "I+1,j-1" when X[i] =x "J"
F "I, J" =max (F[i+1,j],f[i,j-1]) when X "I"! = X "J"
3, calculate the optimal solution
#include <iostream>#include<string.h>using namespacestd;//finding the longest palindrome subsequenceintLspChar*a,intN) { intDp[n][n]; inttem; inti,j; Memset (DP,0,sizeof(DP));//assigning initial values to all DP elements 0 for(i=0; i<n;i++) Dp[i][i]=1; for(i =1; i<n;i++) {tem=0; for(j=0;j< (n-i); J + +){ if(a[j]==a[j+i]) tem= dp[j+1][j+i-1]+2; Elsetem= Max (dp[j+1][j+i],dp[j][j+i-1]); Dp[j][j+i] = tem;//Dp[j][j+i] Longest palindrome subsequence length of x[j][j+i] saved } } returndp[0][n-1];}intMain () {CharA[] ="CHARACTEGKGSAFBDSAFNDSKJAIERQR"; intn =strlen (a); cout<<"The LPs is"<<LSP (a,n) <<Endl;}
4, Structural optimal solution
The value of the optimal solution can be obtained through the above steps. Now only the longest palindrome subsequence length can be output, and the longest palindrome subsequence can not be output directly. One way to do this is to get the inverse of the original sequence, and then use the longest common subsequence method to obtain the longest common subsequence of two sequences.
"Introduction to Algorithms" Dynamic programming