<p>Given a string s, return <em>the number of different non-empty palindromic subsequences in</em> <code>s</code>. Since the answer may be very large, return it <strong>modulo</strong> <code>10<sup>9</sup> + 7</code>.</p>

<p>A subsequence of a string is obtained by deleting zero or more characters from the string.</p>

<p>A sequence is palindromic if it is equal to the sequence reversed.</p>

<p>Two sequences <code>a<sub>1</sub>, a<sub>2</sub>, ...</code> and <code>b<sub>1</sub>, b<sub>2</sub>, ...</code> are different if there is some <code>i</code> for which <code>a<sub>i</sub> != b<sub>i</sub></code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;bccb&quot;
<strong>Output:</strong> 6
<strong>Explanation:</strong> The 6 different non-empty palindromic subsequences are &#39;b&#39;, &#39;c&#39;, &#39;bb&#39;, &#39;cc&#39;, &#39;bcb&#39;, &#39;bccb&#39;.
Note that &#39;bcb&#39; is counted only once, even though it occurs twice.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba&quot;
<strong>Output:</strong> 104860361
<strong>Explanation:</strong> There are 3104860382 different non-empty palindromic subsequences, which is 104860361 modulo 10<sup>9</sup> + 7.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 1000</code></li>
	<li><code>s[i]</code> is either <code>&#39;a&#39;</code>, <code>&#39;b&#39;</code>, <code>&#39;c&#39;</code>, or <code>&#39;d&#39;</code>.</li>
</ul>

class Solution {
public:
    #define id(i)   (s[i] - 'a')

    int countPalindromicSubsequences(string s) {
        // return countPalindromicSubsequences_BruteForce(s);
        return countPalindromicSubsequences_TopDown(s);
    }

    int countPalindromicSubsequences_DP2(string s) {
        // dp[i][j][a] := number of different palindromes in s[i..j] with board a
        return 0;
    }

    int countPalindromicSubsequences_TopDown(string s) {
        // memo[i][j] := number of different palindromes in s[i..j]
        int n = s.length();
        vector<vector<int>> memo(n, vector<int>(n, -1));
        return count(s, 0, n - 1, memo) - 1;  // remove empty string
    }

    int count(const string& s, int start, int end, vector<vector<int>>& memo) {
        if (start > end) return 1;   // null
        if (start == end) return 2;  // null, a
        if (memo[start][end] != -1)
            return memo[start][end];
        // We try to generate new palindromes from existing palindromes in s[start+1, end-1] by 
        // adding boarder chars, i.e., s[start] or s[end] or both to them. But note that when doing 
        // this, we also introduce duplicate palindromes.
        // Case1) s[start] == s[end] == a
        //   We denote all palindromes in s[start+1, end-1] as set P, and A in P as palindromes with boarder a.
        //   When considering s[start] and s[end], we add boarder of a to p in P, e.g., ap or pa or apa to generate new one.
        //   By doing this, we get 2*count(start+1, end-1) palindromes totally. Then we count the duplicacy.
        //   Firstly, duplicate palindromes generated must be those with boarder a in s[start+1, end-1], i.e., A in P.
        //   But are all those palindromes are counted twice? Yes. 
        //   Because, for each p in A, there will be another palindrome q in P such that adding s[start] and s[end] 
        //   to q also results in p. So duplicacy is just the number of palindromes in A in s[start+1, end-1].
        //   count(start, end) = 2*count(start+1, end-1) - |A| + (1 or 0)
        //                     = 2*count(start+1, end-1) - count(start+1, end-1, a) + (1 or 0)
        //   NOTE: also add a if it is not duplicate, i.e., a..[]..a where no boarder char in s[start+1, end-1].
        // Case2) s[start] != start[end]
        //   Since s[start] is different from s[end], we can not add them at the same time. Suppose:
        //   Adding boarder s[start] or s[end] introduces new non-duplicate palindromes Qs or Qe respectively.
        //   But Qs & Qe = null, because p in Qs must has boarder s[start] and p in Qe has boarder s[end], and they
        //   are different boarders. So:
        //   count(start, end) = count(start+1, end-1) + |Qs| + |Qe| 
        //                     = count(start+1, end-1) + 
        //                       (count(start, end-1) - count(start+1, end-1)) +
        //                       (count(start+1, end) - count(start+1, end-1)) 
        //                     = count(start, end-1) + (count(start+1, end) - count(start+1, end-1)
        // Base Case) count(i, j) = 1 if i > j  and  count(i, i) = 2  empty string is also treated as palindrome
        int cnt = 0, kMod = 1e9 + 7;
        if (s[start] == s[end]) {  // case1
            // innerCount := |A|,  #palindromes with boarder s[start] in s[start+1, end-1]
            //   innerCount = count(s, l, r, a) = count(s, l+1, r-1) if s[l]=s[r]=a
            //   innerCount = count([a..a], a) for a..[a..a]..a
            //   innerCount = 0 for a..[]..a or a..[a]..a, where there is no inner boarder
            int l = start + 1, r = end - 1, innerCount = 0;
            while (l < r && s[l] != s[start]) l++;
            while (l < r && s[r] != s[start]) r--;
            if (l < r) innerCount = count(s, l + 1, r - 1, memo);  // found inner boarder, a..[a..a]..a
            if (l > r || s[l] != s[start]) cnt += 1;  // no boarder char, single a is not duplicate, add a
            cnt = (cnt + 2L * count(s, start + 1, end - 1, memo) - innerCount) % kMod;  // count #apa
        } else {  // case2
            cnt = (count(s, start + 1, end, memo) + 
                   count(s, start, end - 1, memo) - 
                   count(s, start + 1, end - 1, memo)) % kMod;
        }
        return memo[start][end] = cnt >= 0 ? cnt : cnt + kMod;
    }

    int countPalindromicSubsequences_BruteForce(string s) {  // O(N^2 * logN)
        // solve(s, i, j, ..) := number of different palindromes including empty string in s[i..j]
        vector<vector<int>> indices(4);  // ordered positions
        for (int i = 0; i < s.length(); i++) {
            indices[s[i] - 'a'].push_back(i);
        }
        return solve(s, 0, s.length() - 1, indices, 0, {}) - 1;  // exclude empty string
    }

    int solve(const string& s, int start, int end, const vector<vector<int>>& indices, 
        int mask, unordered_map<string, int>&& memo) {  // mask: stop pairing if 1
        // memo[i][j] := number of different palindromes in s[i..j]
        // mask := the ith bit of mask indicates whether there exists a pairing char after it, 0 - yes, 1 - no
        int kMod = 1e9 + 7;
        if (start > end) return 1;
        if (start == end) return 2;
        string key = to_string(start) + "#" + to_string(end);
        if (auto it = memo.find(key); it != memo.end())
            return it->second;
        int used = 0, count = 1;  // null as center
        for (int i = start; i <= end; i++) {
            if ((used >> id(i)) & 1) continue;
            used |= (1 << id(i));
            count = (count + 1) % kMod;  // single char as center
            if ((mask >> id(i)) & 1) continue;
            const vector<int>& idxs = indices[id(i)];
            auto pos = upper_bound(idxs.begin(), idxs.end(), end);  // binary search for j
            if (pos != idxs.begin()) {  // new pair
                int j = *(pos - 1);
                if (i >= j) {
                    mask |= (1 << id(i));
                    continue;
                }
                count = (count + solve(s, i + 1, j - 1, indices, mask, move(memo))) % kMod;
            }
        }
        return memo[key] = count;
    }
};
39694