给定一个字符串 s,计算 s 的 不同非空子序列 的个数。因为结果可能很大,所以返回答案需要对 10^9 + 7 取余 。
字符串的 子序列 是经由原字符串删除一些(也可能不删除)字符但不改变剩余字符相对位置的一个新字符串。
- 例如,
"ace"是"abcde"的一个子序列,但"aec"不是。
考虑DP
假设开始有一个空序列(最后统计时-1)
从0开始遍历字符串
将该位置的字符添加到已经生成的字符串之后,再减去重复的字符串
如何统计重复的字符串?
用一个数组dp[26]统计从以每个字符结尾的字符串个数
const int mod = 1e9+7;
class Solution {
public:
int distinctSubseqII(string s) {
int ans = 0;
int n = s.size();
int dp[26];
int cnt = 1;
_for(i,0,26) dp[i] = 0;
_for(i,0,n) {
int t = (cnt - dp[s[i] - 'a'] + mod)%mod;
cnt = (cnt + t)%mod;
dp[s[i] - 'a'] = (dp[s[i] - 'a'] + t)%mod;
}
return (cnt - 1 + mod)%mod;
}
};