Description:
Given a string S, find the number of different non-empty palindromic subsequences in S, and return that number modulo 10^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 sequences A_1, A_2, ... and B_1, B_2, ... are different if there is some i for which A_i != B_i.
Example:
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.
Input:
S = 'abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba'
Output: 104860361
Explanation:
There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.
Link:
https://leetcode.com/problems/count-different-palindromic-subsequences/description/
解题方法:
参考 http://zxi.mytechroad.com/blog/dynamic-programming/leetcode-730-count-different-palindromic-subsequences/
与允许duplicate的版本相似,当左右不相等时:DP[start][end] = DP[start + 1][end] + DP[start][end - 1] - DP[start + 1][end - 1];
当左右相等时,有三种情况:
a xxxx a
DP[start][end] = 2 * DP[start + 1][end - 1] + 2;
除了乘2以外,还多了a与aa
a xxxa a
DP[start][end] = 2 * DP[start + 1][end - 1] + 1;
多了一个aa
a axxa a
DP[start][end] = 2 * DP[start + 1][end - 1] - DP[left + 1][right - 1];
需要减去中间aa之间重叠的部分
Tips:
每次都 + 再 %,防止数据过大
Time Complexity:
O(n ^ 3)
完整代码:
int countPalindromicSubsequences(string S) {
int len = S.size();
if(!len)
return 0;
vector<vector<int>> DP(len, vector<int>(len, 0));
long int M=1000000007;
for(int i = 0; i < len; i++)
DP[i][i] = 1;
for(int l = 2; l <= len; l++) {
for(int start = 0; start + l - 1 < len; start++) {
int end = start + l - 1;
if(S[start] == S[end]) {
int cnt = 0;
int left = start + 1;
int right = end - 1;
while(left <= right && S[left] != S[start]) left++;
while(left <= right && S[right] != S[start]) right--;
if(left > right)
DP[start][end] = 2 * DP[start + 1][end - 1] + 2;
else if(left == right)
DP[start][end] = 2 * DP[start + 1][end - 1] + 1;
else
DP[start][end] = 2 * DP[start + 1][end - 1] - DP[left + 1][right - 1];
}
else
DP[start][end] = DP[start + 1][end] + DP[start][end - 1] - DP[start + 1][end - 1];
DP[start][end] = (DP[start][end] + M) % M;
}
}
return DP[0][len - 1];
}
网友评论