|
| 1 | +# 940. Distinct Subsequences II |
| 2 | +Given a string s, return *the number of **distinct non-empty subsequences** of* `s`. Since the answer may be very large, return it **modulo** <code>10<sup>9</sup> + 7</code>. |
| 3 | + |
| 4 | +A **subsequence** of a string is a new string that is formed from the original string by deleting some (can be none) of the characters without disturbing the relative positions of the remaining characters. (i.e., `"ace"` is a subsequence of `"abcde"` while `"aec"` is not. |
| 5 | + |
| 6 | +#### Example 1: |
| 7 | +<pre> |
| 8 | +<strong>Input:</strong> s = "abc" |
| 9 | +<strong>Output:</strong> 7 |
| 10 | +<strong>Explanation:</strong> The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc". |
| 11 | +</pre> |
| 12 | + |
| 13 | +#### Example 2: |
| 14 | +<pre> |
| 15 | +<strong>Input:</strong> s = "aba" |
| 16 | +<strong>Output:</strong> 6 |
| 17 | +<strong>Explanation:</strong> The 6 distinct subsequences are "a", "b", "ab", "aa", "ba", and "aba". |
| 18 | +</pre> |
| 19 | + |
| 20 | +#### Example 3: |
| 21 | +<pre> |
| 22 | +<strong>Input:</strong> s = "aaa" |
| 23 | +<strong>Output:</strong> 3 |
| 24 | +<strong>Explanation:</strong> The 3 distinct subsequences are "a", "aa" and "aaa". |
| 25 | +</pre> |
| 26 | + |
| 27 | +#### Constraints: |
| 28 | +* `1 <= s.length <= 2000` |
| 29 | +* `s` consists of lowercase English letters. |
| 30 | + |
| 31 | +## Solutions (Rust) |
| 32 | + |
| 33 | +### 1. Solution |
| 34 | +```Rust |
| 35 | +impl Solution { |
| 36 | + pub fn distinct_subseq_ii(s: String) -> i32 { |
| 37 | + const MOD: i32 = 1_000_000_007; |
| 38 | + let n = s.len(); |
| 39 | + let mut last_index = [n; 26]; |
| 40 | + let mut dp = vec![0_i32; n + 1]; |
| 41 | + dp[n] = -1; |
| 42 | + |
| 43 | + for (i, c) in s.bytes().map(|c| (c - b'a') as usize).enumerate() { |
| 44 | + dp[i + 1] = (dp[i] * 2 - dp[last_index[c]]).rem_euclid(MOD); |
| 45 | + last_index[c] = i; |
| 46 | + } |
| 47 | + |
| 48 | + *dp.last().unwrap() |
| 49 | + } |
| 50 | +} |
| 51 | +``` |
0 commit comments