730.Count Different Palindromic Subsequences

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值