当前位置:网站首页>730.Count Different Palindromic Subsequences

730.Count Different Palindromic Subsequences

2022-06-11 23:57:00 SUNNY_CHANGQI

The description of the porblem

Given a string s, return the number of different non-empty palindromic subsequences in s. 
Since the answer may be very large, return it modulo 1e9+7
A sequence is palindromic if it is equal to the sequence reversed. 

Two sequences a1, a2. ⋯ \cdots and b1, b2, ⋯ \cdots are different if there is some i i i for which ai ! = != != bi.

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.

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/count-different-palindromic-subsequences

The intuition (dynamic programming)

The codes;

#include <string>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
    
public:
    int countPalindromicSubsequences(string s) {
    
        const int MODE = 1e9 + 7;
        int n = s.size();
        vector<vector<vector<int>>> dp(4, vector<vector<int>>(n, vector<int>(n, 0)));
        for (int i = 0; i < n; i++) {
    
            dp[s[i] - 'a'][i][i] = 1;
        }
        for (int len = 2; len <= n; ++len) {
    
            for (int i = 0, j = len -1; j < n; ++i, ++j) {
    
                for (char c = 'a', k = 0; c < 'e'; ++c, ++k) {
    
                    if (s[i] == c && s[j] == c) {
    
                        dp[k][i][j] = 2LL + (dp[0][i+1][j-1] + dp[1][i+1][j-1] + dp[2][i+1][j-1] + dp[3][i+1][j-1]) % MODE;
                    } else if (s[i] == c && s[j] != c) {
    
                        dp[k][i][j] = dp[k][i][j-1];
                    } else if (s[i] != c && s[j] == c) {
    
                        dp[k][i][j] = dp[k][i+1][j];
                    } else {
    
                        dp[k][i][j] = dp[k][i+1][j-1];
                    }
                }
            }
        }
        int res(0);
        for (int i = 0; i < 4; ++i) {
    
            res += dp[i][0][n-1];
            res %= MODE;
        }
        return res;
    }
};
int main() {
    
    Solution s;
    //"bcbacbabdcbcbdcbddcaaccdcbbcdbcabbcdddadaadddbdbbbdacbabaabdddcaccccdccdbabcddbdcccabccbbcdbcdbdaada"
    string s1 = "bcbacbabdcbcbdcbddcaaccdcbbcdbcabbcdddadaadddbdbbbdacbabaabdddcaccccdccdbabcddbdcccabccbbcdbcdbdaada";
    cout << "res: " << s.countPalindromicSubsequences(s1) << endl;
    return 0;
}

#The results

$ ./test
res: 823023321
原网站

版权声明
本文为[SUNNY_CHANGQI]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_38396940/article/details/125231583