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​

​题解:​

​官方题解动态规划算法,从第一个开始,如果s[i]未出现过,那么dp[i] = 2^i - 1,如果s[i]出现过那么就是减去上次出现时k的dp[k],即dp[i] - dp[k]。​

​c++:​

class Solution {
public:
int distinctSubseqII(string S) {
int n = S.length();
if (n < 2) {
return n;
}
int mod = 1e9 + 7;
vector<int> last(26, -1);
vector<long long> dp(n + 1, 1);
for (int i = 0; i < n; i++) {
int k = S[i] - 'a';
dp[i + 1] = dp[i] * 2 % mod;
if (last[k] != -1) {
dp[i + 1] = (dp[i + 1] - dp[last[k]]) % mod;
}
last[k] = i;
}
return (dp[n] - 1 + mod) % mod;
}
};

go:

func distinctSubseqII(S string) int {
var mod int = 1e9 + 7
l := len(S)
dp := make([]int, l + 1)
last := make([]int, 26)
for i := 0; i < 26; i++ {
last[i] = -1
}
dp[0] = 1
for i := 0; i < l; i++ {
k := S[i] - 'a'
dp[i + 1] = dp[i] * 2 % mod
if last[k] != -1 {
dp[i + 1] = (dp[i + 1] - dp[last[k]] + mod) % mod
}
last[k] = i
}
dp[l]--
return (dp[l] + mod) % mod
}