The main difficulty is we have to find the length of longest palindromic subsequence, but not a substring. Which means the sequence may not be continuous. There are many ways to do, but using dynamic programming, the method is concise but hard to come up with. We first use a 2d array length[i][j] to store the length of each subsequence, with i, j means the length of longest PS between i and j in the string. The recurrence part add the length by 2 when the number left and right of the current sequence is the same and when not, the bigger one is chosen. The initial state is length[i][i]=1.
class Solution {
public:
int longestPalindromeSubseq(string s) {
int l = s.length();
int length[1000][1000];
for(int i=l-1;i>=0;i--){
length[i][i]=1;
for(int j=i+1;j<l;j++){
if(s[i]==s[j])
length[i][j]=length[i+1][j-1]+2;
else
length[i][j]=max(length[i+1][j],length[i][j-1]);
}
}
return length[0][l-1];
}
};