Given a string
S
, count the number of distinct, non-empty subsequences ofS
.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
Approach #1: Math. [Java]
class Solution {
public int distinctSubseqII(String S) {
long end[] = new long[26], mod = (long)1e9 + 7;
for (char c : S.toCharArray())
end[c - 'a'] = Arrays.stream(end).sum()%mod + 1;
return (int)(Arrays.stream(end).sum()%mod);
}
}
Analysis:
Reference: