LeetCode 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:
S contains only lowercase letters.
1 <= S.length <= 2000
假设dp[i]存的是当前答案的数字
public int distinctSubseqII(String s) {
int m = (int)Math.pow(10,9) + 7;
List<List<Integer>> map = new ArrayList<>();
for (int i =0; i< 26; i++){
map.add(new ArrayList<>());
}
int [] dp = new int[s.length()];
for (int i = 0; i < s.length(); i++) {
if (i == 0) {
dp[i] = 1;
} else {
dp[i] = 2 * dp[i-1] + 1;
if (map.get(s.charAt(i) - 'a').size() != 0) {
for (int index : map.get(s.charAt(i) - 'a')) {
if (index > 0) {
dp[i] = dp[i] - dp[index] + dp[index - 1];
} else {
dp[i] = dp[i] - dp[index];
}
}
}
}
//System.out.println("dp["+i+"]: " + dp[i]);
map.get(s.charAt(i) - 'a').add(i);
}
return dp[s.length() - 1];
}
a, b, a, b
a b aa bb
ab ba aab
aba bab
abab
abb
假设dp[i]存的是当前新增的数目
public int distinctSubseqII(String s) {
int m = (int)Math.pow(10,9) + 7;
int[] dp = new int[s.length()];
for(int i = 0; i < s.length(); ++i) {
dp[i] = 1;
for(int j = 0; j < i; ++j) {
if(s.charAt(i) != s.charAt(j)) {
dp[i] += dp[j];
dp[i] %= m;
}
}
}
int sum = 0;
for(int i = 0;i < dp.length; ++i) {
sum += dp[i];
sum %= m;
}
return sum;
}