The question is like this--
For every string given as input, you need to tell the number of subsequences of it that are palindromes (need not necessarily be distinct). N
Intuitive O(n^3) solution using DP:
Let each state dp(i,j) represents number of palindromic subsequences in string[i...j] Then simple recursive formula is
for k in range i, j-1:
if(A[j]==A[k]){
dp(i,j) = dp(i,j) + dp(k+1,j-1);
The Idea is very simple.. For adding a new character check if it is end of a subsequence or not. If there exist same character in the previously computed smaller subproblem, then it add the number of subsequences contained in range (k+1,j-1). Just take care of corner cases. Add one as newly added character is a single character subsequence too. Even if there are no subsequences in the range (k+1,j-1) , you would still get 1 new subsequences of length 2 (like "aa").