Formatted question description: https://leetcode.ca/all/730.html

# 730. Count Different Palindromic Subsequences (Hard)

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 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:
Output: 104860361
Explanation:
There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10^9 + 7.


Note:

• The length of S will be in the range [1, 1000].
• Each character S[i] will be in the set {'a', 'b', 'c', 'd'}.
• Related Topics:
String, Dynamic Programming

Similar Questions:

## Solution 1. DP

First consider the case where we count duplicates as well.

Let dp[i][j] be the number of palindromic subsequences in S[i..j].

dp[i][j] = 0   if i > j
dp[i][i] = 1


If S[i] != S[j]:

dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1]


We need to - dp[i + 1][j - 1] because the palindromic subsequences are counted twice already in dp[i + 1][j] and dp[i][j - 1].

If S[i] == S[j], then there are additional dp[i + 1][j - 1] + 1 cases where are the palindromic subsequences in S[(i+1)..(j-1)] wrapped with S[i] and S[j], plus one case S[i]S[j].

dp[i][j] = dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1] + (dp[i + 1][j - 1] + 1)
= dp[i + 1][j] + dp[i][j - 1] + 1


So in sum, dp[i][j] = :

• 0, if i > j
• 1, if i == j
• dp[i + 1][j] + dp[i][j - 1] - dp[i + 1][j - 1], if S[i] != S[j]
• dp[i + 1][j] + dp[i][j - 1] + 1, if S[i] == S[j]

Now consider distinct count.

dp[i][j][k] is the number of distinct palindromic subsequences in S[i..j] bordered by 'a' + k.

If S[i] != S[j]:

dp[i][j][k] = dp[i+1][j][k] + dp[i][j-1][k] - dp[i+1][j-1][k]


If S[i] == S[j] && S[i] == 'a' + k:

dp[i][j][k] = 2 + sum( dp[i+1][j-1][t] | 0 <= t < 4 )


This is because we can wrap all the cases of dp[i+1][j-1][t] with S[i] and S[j] to form new palindromes (which won’t contain a and aa), and the +2 means a and aa.

So in sum, dp[i][j][k] =:

• 0, if i > j or i == j && S[i] != 'a' + k
• 1, if i == j && S[i] == 'a' + k
• dp[i+1][j][k] + dp[i][j-1][k] - dp[i+1][j-1][k], if S[i] != S[j]
• 2 + sum( dp[i+1][j-1][t] | 0 <= t < 4 ), if S[i] == S[j] && S[i] == 'a' + k
// OJ: https://leetcode.com/problems/count-different-palindromic-subsequences/
// Time: O(N^2)
// Space: O(N^2)
// Ref: https://leetcode.com/problems/count-different-palindromic-subsequences/discuss/272297/DP-C%2B%2B-Clear-solution-explained
int memo;
class Solution {
int mod = 1e9 + 7;
string s;
int dp(int first, int last, int ch) {
if (first > last) return 0;
if (first == last) return s[first] - 'a' == ch;
if (memo[first][last][ch] != -1) return memo[first][last][ch];
int ans = 0;
if (s[first] == s[last] && s[first] - 'a' == ch) {
ans = 2;
for (int i = 0; i < 4; ++i) ans = (ans + dp(first + 1, last - 1, i)) % mod;
} else {
ans = (ans + dp(first, last - 1, ch)) % mod;
ans = (ans + dp(first + 1, last, ch)) % mod;
ans = (ans - dp(first + 1, last - 1, ch)) % mod;
if (ans < 0) ans += mod;
}
return memo[first][last][ch] = ans;
}
public:
int countPalindromicSubsequences(string S) {
s = S;
memset(memo, -1, sizeof(memo));
int ans = 0;
for (int i = 0; i < 4; ++i) ans = (ans + dp(0, S.size() - 1, i)) % mod;
return ans;
}
};


Java

• class Solution {
public int countPalindromicSubsequences(String S) {
final int MODULO = 1000000007;
int length = S.length();
int[][] dp = new int[length][length];
for (int i = 0; i < length; i++)
dp[i][i] = 1;
for (int i = length - 2; i >= 0; i--) {
char c1 = S.charAt(i);
for (int j = i + 1; j < length; j++) {
char c2 = S.charAt(j);
if (c1 == c2) {
int low = i + 1, high = j - 1;
while (low <= high && S.charAt(low) != c1)
low++;
while (low <= high && S.charAt(high) != c2)
high--;
if (low > high)
dp[i][j] = dp[i + 1][j - 1] * 2 + 2;
else if (low == high)
dp[i][j] = dp[i + 1][j - 1] * 2 + 1;
else
dp[i][j] = dp[i + 1][j - 1] * 2 - dp[low + 1][high - 1];
} else
dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1];
dp[i][j] %= MODULO;
if (dp[i][j] < 0)
dp[i][j] += MODULO;
}
}
return dp[length - 1];
}
}

• // OJ: https://leetcode.com/problems/count-different-palindromic-subsequences/
// Time: O(N^2)
// Space: O(N^2)
// Ref: https://leetcode.com/problems/count-different-palindromic-subsequences/discuss/272297/DP-C%2B%2B-Clear-solution-explained
int memo;
class Solution {
int mod = 1e9 + 7;
string s;
int dp(int first, int last, int ch) {
if (first > last) return 0;
if (first == last) return s[first] - 'a' == ch;
if (memo[first][last][ch] != -1) return memo[first][last][ch];
int ans = 0;
if (s[first] == s[last] && s[first] - 'a' == ch) {
ans = 2;
for (int i = 0; i < 4; ++i) ans = (ans + dp(first + 1, last - 1, i)) % mod;
} else {
ans = (ans + dp(first, last - 1, ch)) % mod;
ans = (ans + dp(first + 1, last, ch)) % mod;
ans = (ans - dp(first + 1, last - 1, ch)) % mod;
if (ans < 0) ans += mod;
}
return memo[first][last][ch] = ans;
}
public:
int countPalindromicSubsequences(string S) {
s = S;
memset(memo, -1, sizeof(memo));
int ans = 0;
for (int i = 0; i < 4; ++i) ans = (ans + dp(0, S.size() - 1, i)) % mod;
return ans;
}
};

• class Solution:
def countPalindromicSubsequences(self, S):
"""
:type S: str
:rtype: int
"""
def count(S, i, j):
if i > j: return 0
if i == j: return 1
if self.m_[i][j]:
return self.m_[i][j]
if S[i] == S[j]:
ans = count(S, i + 1, j - 1) * 2
l = i + 1
r = j - 1
while l <= r and S[l] != S[i]: l += 1
while l <= r and S[r] != S[i]: r -= 1
if l > r: ans += 2
elif l == r: ans += 1
else: ans -= count(S, l + 1, r - 1)
else:
ans = count(S, i + 1, j) + count(S, i, j - 1) - count(S, i + 1, j - 1)

self.m_[i][j] = ans % (10 ** 9 + 7)
return self.m_[i][j]

n = len(S)
self.m_ = [[None for _ in range(n)] for _ in range(n)]
return count(S, 0, n - 1)