/**
* Problem: LeetCode 940 - Distinct Subsequences II
* Difficulty: Hard
* Language: Java
* Author: CodeByTushu
*/
class Solution {
public int distinctSubseqII(String s) {
long MOD = 1_000_000_007;
long[] dp = new long[26];
for (char ch : s.toCharArray()) {
int c = ch - 'a';
long total = 1;
for (int i = 0; i < 26; i++) {
total = (total + dp[i]) % MOD;
}
dp[c] = total;
}
long ans = 0;
for (int i = 0; i < 26; i++) {
ans = (ans + dp[i]) % MOD;
}
return (int) ans;
}
}
"""
Problem: LeetCode 940 - Distinct Subsequences II
Difficulty: Hard
Language: Python
Author: CodeByTushu
"""
class Solution:
def distinctSubseqII(self, s: str) -> int:
MOD = 1_000_000_007
dp = [0] * 26
for ch in s:
c = ord(ch) - ord('a')
total = 1
for count in dp:
total = (total + count) % MOD
dp[c] = total
ans = sum(dp) % MOD
return ans
/**
* Problem: LeetCode 940 - Distinct Subsequences II
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
#include <string>
#include <vector>
using namespace std;
/**
* Problem: LeetCode 940 - Distinct Subsequences II
* Difficulty: Hard
* Language: C++
* Author: CodeByTushu
*/
class Solution {
public:
int distinctSubseqII(string s) {
long long MOD = 1'000'000'007;
vector<long long> dp(26, 0);
for (char ch : s) {
int c = ch - 'a';
long long total = 1;
for (int i = 0; i < 26; i++) {
total = (total + dp[i]) % MOD;
}
dp[c] = total;
}
long long ans = 0;
for (int i = 0; i < 26; i++) {
ans = (ans + dp[i]) % MOD;
}
return static_cast<int>(ans);
}
};
/**
* Problem: LeetCode 940 - Distinct Subsequences II
* Difficulty: Hard
* Language: JavaScript
* Author: CodeByTushu
*/
var distinctSubseqII = function(s) {
const MOD = 1000000007n;
const dp = new Array(26).fill(0n);
for (let i = 0; i < s.length; i++) {
const c = s.charCodeAt(i) - 97;
let total = 1n;
for (let j = 0; j < 26; j++) {
total = (total + dp[j]) % MOD;
}
dp[c] = total;
}
let ans = 0n;
for (let i = 0; i < 26; i++) {
ans = (ans + dp[i]) % MOD;
}
return Number(ans);
};