classSolution{public:intcountPalindromicSubsequences(strings){constexprintkMod=1'000'000'007;constintn=s.length();// dp[i][j] := # of different non-empty palindromic subseqs in s[i..j]vector<vector<int>>dp(n,vector<int>(n));for(inti=0;i<n;++i)dp[i][i]=1;for(intd=1;d<n;++d)for(inti=0;i+d<n;++i){constintj=i+d;if(s[i]==s[j]){intlo=i+1;inthi=j-1;while(lo<=hi&&s[lo]!=s[i])++lo;while(lo<=hi&&s[hi]!=s[i])--hi;if(lo>hi)dp[i][j]=dp[i+1][j-1]*2+2;elseif(lo==hi)dp[i][j]=dp[i+1][j-1]*2+1;elsedp[i][j]=dp[i+1][j-1]*2-dp[lo+1][hi-1];}else{dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1];}dp[i][j]=(dp[i][j]+kMod)%kMod;}returndp[0][n-1];}};
classSolution{publicintcountPalindromicSubsequences(Strings){finalintkMod=1_000_000_007;finalintn=s.length();// dp[i][j] := # of different non-empty palindromic subseqs in s[i..j]int[][]dp=newint[n][n];for(inti=0;i<n;++i)dp[i][i]=1;for(intd=1;d<n;++d)for(inti=0;i+d<n;++i){finalintj=i+d;if(s.charAt(i)==s.charAt(j)){intlo=i+1;inthi=j-1;while(lo<=hi&&s.charAt(lo)!=s.charAt(i))++lo;while(lo<=hi&&s.charAt(hi)!=s.charAt(i))--hi;if(lo>hi)dp[i][j]=dp[i+1][j-1]*2+2;elseif(lo==hi)dp[i][j]=dp[i+1][j-1]*2+1;elsedp[i][j]=dp[i+1][j-1]*2-dp[lo+1][hi-1];}else{dp[i][j]=dp[i][j-1]+dp[i+1][j]-dp[i+1][j-1];}dp[i][j]=(int)((dp[i][j]+kMod)%kMod);}returndp[0][n-1];}}