Given a string S, find the number of different non-empty palindromic subsequences in S, and return that number modulo10^9 + 7.
A subsequence of a string S is obtained by deleting 0 or more characters from S.
A sequence is palindromic if it is equal to the sequence reversed.
Two sequencesA_1, A_2, ...andB_1, B_2, ...are different if there is someifor whichA_i != B_i.
Example 1:
Input:S = 'bccb'
Output: 6
Explanation:
The 6 different non-empty palindromic subsequences are 'b', 'c', 'bb', 'cc', 'bcb', 'bccb'.
Note that 'bcb' is counted only once, even though it occurs twice.
Example 2:
Input:S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba'
Output: 104860361
Explanation:
There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.
Note:
The length ofSwill be in the range[1, 1000].
Each characterS[i]will be in the set{'a', 'b', 'c', 'd'}.
int k =1000000000+7;publicintcountPalindromicSubsequences(String S) {if (S ==null||S.length() ==0) {return0; }int n =S.length();int[][] memo =newint[n][n]; returncount(S,0, n -1, memo);}privateintcount(String S,int s,int e,int[][] memo) { if (s > e) { return0; }if (s == e) { memo[s][e] =1;return1; }if (memo[s][e] >0) {return memo[s][e]; }long res =0;if (S.charAt(s) ==S.charAt(e)) { res =2*count(S, s +1, e -1, memo);int l = s +1;int r = e -1;while (l <= r &&S.charAt(l) !=S.charAt(s)) { l++; }while (l <= r &&S.charAt(r) !=S.charAt(s)) { r--; }if (l > r) { res = res +2; } elseif (l == r) { res = res +1; } elseif (l < r) { res = res -count(S, l +1, r -1, memo); } } else { res =count(S, s +1, e, memo)+count(S, s, e -1, memo)-count(S, s +1, e -1, memo); } res = (res + k) % k; memo[s][e] = (int)res;return memo[s][e];}
贴一个递推作为参考:原code出自花花酱
// Author: Huahua// Runtime: 79 msclassSolution {public:intcountPalindromicSubsequences(conststring& S) {int n =S.length(); vector<vector<int>>dp(n,vector<int>(n,0));for (int i =0; i < n; ++i)dp[i][i] =1;for (int len =1; len <= n; ++len) {for (int i =0; i < n - len; ++i) {constint j = i + len; if (S[i] ==S[j]) {dp[i][j] =dp[i +1][j -1] *2; int l = i +1;int r = j -1;while (l <= r &&S[l] !=S[i]) ++l;while (l <= r &&S[r] !=S[i]) --r; if (l == r) dp[i][j] +=1;elseif (l > r) dp[i][j] +=2;elsedp[i][j] -=dp[l +1][r -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]; }private:staticconstexprlong kMod =1000000007; };