-
Notifications
You must be signed in to change notification settings - Fork 985
/
Copy pathCount Palindromic Subsequences.cpp
67 lines (54 loc) · 1.78 KB
/
Count Palindromic Subsequences.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
Given a string str of length N,
you have to find number of palindromic subsequence
(need not necessarily be distinct) which could be formed from the string s.
Note: You have to return the answer module 109+7;
Input : str = "aab"
Output : 4
Explanation :- palindromic subsequence are :"a", "a", "b", "aa"
*/
#include <bits/stdc++.h>
using namespace std;
long long int countPS(string s)
{
long long int n=s.length(),i,j,l,m=1000000007;
// create a 2D array to store the count of palindromic subsequence
long long int dp[n+1][n+1];
memset(dp,0,sizeof(dp));
for(l=1;l<=n;l++)
{
for(i=0;l+i<=n;i++)
{
j=i+l-1;
// palindromic subsequence of length 1
if(l==1)
dp[i][i]=1;
// palindromic subsequence of length 2
else if(l ==2)
{
if(s[i]==s[j])
dp[i][j]=3;
else
dp[i][j]=2;
}
// check subsequence of length L is palindrome or not
else if(s[i]==s[j])
dp[i][j]=dp[i+1][j]+dp[i][j-1]+1;
else
dp[i][j]=dp[i+1][j]+dp[i][j-1]-dp[i+1][j-1];
dp[i][j]+=m;
dp[i][j]%=m;
}
}
// return total palindromic subsequence
return dp[0][n-1];
}
// Driver code
int main()
{
string s;
cin>>s;
cout << "Total palindromic subsequence are : "
<< countPS(s) << endl;
return 0;
}