
Input: 's' = "pqqr"
Output: 5
Explanation: The subsequences are:
p
q
q
r
qq
Please note that both "q" are considered different.
The first line contains a string 's'.
Print the number of non-empty palindromic subsequences modulo 10 ^ 9 + 7.
You do not need to print anything; it has already been taken care of. Just implement the given function.
The basic idea of this approach is to break the original problem into sub-problems. Let us assume we want to find the number of palindromic subsequences in string 's' whose length is |s|.
Now, let us define a recursive function
count(int i, int j, string &s)Which returns the number of palindromic subsequences in the substring [i:j] of string 's'.
We can append 's[i]' and 's[j]' at the front and back respectively in any palindromic subsequence of substring [i + 1, j - 1] and generate a new palindromic subsequence i.e. add count(i + 1, j - 1, s) + 1. Note 1 is added because a pair of characters ('s[i]', 's[j]') will make a palindrome.
We’ll observe that there are some redundant function calls which means that there are some overlapping subproblems. The repetition of such sub-problems suggests that we can use dynamic programming to optimize our approach.
The key idea behind a dynamic programming approach is to use memoization, i.e. we’ll save the result of our sub-problem in a matrix so that it can be used later on.
Let 'dp[i][j]' be our dynamic programming matrix to store the number of palindromic subsequences in substring [i, j] of the given string 's'. It will help us to avoid redundant function calls.
We can append 's[i]' and 's[j]' at the front and back respectively in any palindromic subsequence of substring [i + 1, j - 1] and generate a new palindromic subsequence i.e. add count(i + 1, j - 1, s) + 1. Note 1 is added because a pair of characters ('s[i]', 's[j]') will make a palindrome.
The basic idea here is to use a bottom-up dynamic programming approach to solve the problem. The recursion function is discussed in the above mentioned approach.
Let 'dp[i][j]' be our dynamic programming matrix to store the number of palindromic subsequences in substring [i, j] of the given string 's'.