# 940. Distinct Subsequences II

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`

``````class Solution {
public:
int distinctSubseqII(string S) {
int M = 1e9 + 7;
vector<int> dp(26);
for (char c : S) {
dp[c - 'a'] = accumulate(dp.begin(), dp.end(), 1L) % M;
}
return accumulate(dp.begin(), dp.end(), 0L) % M;
}
};
``````

``````class Solution {
public:
int distinctSubseqII(string S) {
int n = S.size(), res = 0, M = 1e9 + 7;
unordered_map<char, long> m;
vector<long> a(n), b(n);
a[0] = 1;
m[S[0]] = 0;
for (int i = 1; i < n; ++i) {
b[i] = (a[i - 1] + b[i - 1]) % M;
if (!m.count(S[i])) {
a[i] = (b[i] + 1) % M;
} else {
a[i] = (M + b[i] - m[S[i]]) % M;
}
m[S[i]] = b[i];
}
return (a.back() + b.back()) % M;
}
};
``````

Github 同步地址:

https://github.com/grandyang/leetcode/issues/940

Distinct Subsequences

https://leetcode.com/problems/distinct-subsequences-ii/

https://leetcode.com/problems/distinct-subsequences-ii/discuss/192017/C%2B%2BJavaPython-4-lines-O(N)-Time-O(1)-Space

https://leetcode.com/problems/distinct-subsequences-ii/discuss/192030/Java-DP-O(N2)-time-greater-O(N)-time-greater-O(1)-space

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation