Palindrome subsequence (区间dp)

本文介绍了一种使用动态规划解决回文子序列计数问题的方法。通过区间DP技术,文章详细阐述了如何求解一个字符串中不同回文子序列的数量,并提供了C++实现代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Palindrome subsequence

In mathematics, a subsequence is a sequence that can be derived from another sequence by deleting some elements without changing the order of the remaining elements. For example, the sequence <A, B, D> is a subsequence of <A, B, C, D, E, F>.
(http://en.wikipedia.org/wiki/Subsequence)

Given a string S, your task is to find out how many different subsequence of S is palindrome. Note that for any two subsequence X = <S x1, S x2, ..., S xk> and Y = <S y1, S y2, ..., S yk> , if there exist an integer i (1<=i<=k) such that xi != yi, the subsequence X and Y should be consider different even if S xi = S yi. Also two subsequences with different length should be considered different.

Input The first line contains only one integer T (T<=50), which is the number of test cases. Each test case contains a string S, the length of S is not greater than 1000 and only contains lowercase letters. Output For each test case, output the case number first, then output the number of different subsequence of the given string, the answer should be module 10007. Sample Input
4
a
aaaaa
goodafternooneveryone
welcometoooxxourproblems
Sample Output
Case 1: 1
Case 2: 31
Case 3: 421
Case 4: 960

思路:注意到任意一个回文子序列收尾两个字符一定是相同的,于是可以区间dp,用dp[i][j]表示原字符串中[i,j]位置中出现的回文子序列的个数,有递推关系:

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

如果i和j位置出现的字符相同,那么dp[i][j]可以由dp[i+1][j-1]中的子序列加上这两个字符构成回文子序列,再加上i,j位置组成的回文子序列,也就是

dp[i][j]+=dp[i+1][j-1]+1,注意边界特判一下就可以了

但是需要注意的一点是这个题用地dfs写并不是特别优化,用c++提交可以过,中间的取模运算如果取模会超时,改成减法就可以过(虽然加减法比乘除快但是没想到时间卡的这么严?)否则会超时
code:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1010;
const int mod = 10007;
int dp[maxn][maxn];
char str[maxn];
int dfs(int l,int r){
    if(l > r) return 0;
    if(l == r) return 1;
    if(dp[l][r] != -1) return dp[l][r];//记忆化搜索
    dp[l][r] = (dfs(l+1,r) + dfs(l,r-1) - dfs(l+1,r-1));
    if(str[l] == str[r]){
        dp[l][r] += (dfs(l+1,r-1) + 1);
        //相当于又可以以lr为两端和中间的所有已有回文序列构成新的回文序列
        //dfs(l+1,r-1)是两个端点和中间任意回文序列构成的新序列
        //+1是两个端点单独存在构成的一个长度为2的回文序列
    }
    while(dp[l][r] >= mod){
        dp[l][r] -= mod;//模运算改成减法运算
    }
    while(dp[l][r] < 0)
        dp[l][r] += mod;
    return dp[l][r];
}
int main(){
    int t;
    int cas = 0;
    scanf("%d",&t);
    while(t--){
        printf("Case %d: ",++cas);
        scanf("%s",str+1);
        int len = strlen(str+1);
        for(int i = 0; i <= len; i++){
            for(int j = 0; j <= len; j++){
                dp[i][j] = -1;
            }
        }
        printf("%d\n",dfs(1,len));
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值