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:
- S contains only lowercase letters.
- 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;
}
};