leetcode 940. Distinct Subsequences II

子序列计数算法
本文介绍了一种使用动态规划算法来计算给定字符串中所有非空、不同子序列数量的方法。通过构建DP数组,该算法能够高效地解决可能产生大量结果的问题,并返回答案模10^9+7的结果。示例包括了abc、aba和aaa等字符串的子序列计数。

Given a string S, count the number of distinct, non-empty subsequences of S .

Since the result may be large, return the answer modulo 10^9 + 7.

Example 1:

Input: "abc"
Output: 7
Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc".

Example 2:

Input: "aba"
Output: 6
Explanation: The 6 distinct subsequences are "a", "b", "ab", "ba", "aa" and "aba".

Example 3:

Input: "aaa"
Output: 3
Explanation: The 3 distinct subsequences are "a", "aa" and "aaa".

Note:

  1. S contains only lowercase letters.
  2. 1 <= S.length <= 2000

求给出字符串的所有子串的个数
设计DP数组 dp[i][j]: 在位置 i 前以字符 j+‘a’ 结尾的子串的数量。
这样不难得出,位置 i 前以 s[i] 结尾的子串的数量 等于 位置[i-1] 上所有子串的数量 加 仅由 s[i] 自身构成的集合,即

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

class Solution {
private:
    const int mod=1e9+7;
public:
    int distinctSubseqII(string s) {
        int len=s.size();
        vector<vector<long long> > dp(len,vector<long long>(26,0));
        dp[0][s[0]-'a']=1;
        for(int i=1;i<len;i++)
            for(char c='a';c<='z';c++){
                if(c==s[i])
                    dp[i][c-'a']=(dp[i][c-'a']+getSum(dp[i-1])+1)%mod;
                else
                    dp[i][c-'a']=dp[i-1][c-'a'];
            }
        return getSum(dp[len-1]);
    }
    int getSum(vector<long long>& a){
        long long sum=0;
        for(auto ele : a){
            sum=(sum+ele)%mod;
        }
        return sum%mod;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值