20221014 - 940. Distinct Subsequences II 不同的子序列 2(动态规划)

120 阅读1分钟

Given a string s, return the number of distinct non-empty subsequences of s. Since the answer may be very large, return it modulo 1e9 + 7.

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.

Example 1

Input: s = "abc"
Output: 7
Explanation: The 7 distinct subsequences are "a", "b", "c", "ab", "ac", "bc", and "abc".

Example 2

Input: s = "aba"
Output: 6
Explanation: The 6 distinct subsequences are "a", "b", "ab", "aa", "ba", and "aba".

Example 3

Input: s = "aaa"
Output: 3
Explanation: The 3 distinct subsequences are "a", "aa" and "aaa".

Constraints

  • 1 <= s.length <= 2000
  • s consists of lowercase English letters.

Solution

f[i] 表示第 i 个字符作为最后一个字符时的子序列个数,last[i] 是随着遍历一起更新的而不是一开始就确定好的。

初始化 f[i] = 1 ,每次都加一遍 last[i] 然后更新 last[i]

是前面的全都生成好了,然后加上下一个字符以后的情况。

就是当前 f[i] 是前面已经遍历过的子序列之和,但是是用 f[last[j]] 来加和。

#define MOD 1000000007
int distinctSubseqII(char * s){
    int i, j, n, ans, last[26];
    n = strlen(s);
    int f[n];
    for (i = 0; i < 26; i++) last[i] = -1;
    for (i = 0; i < n; i++) f[i] = 1;
    for (i = 0; i < n; i++) {
        for (j = 0; j < 26; j++) {
            if (last[j] != -1) f[i] = (f[i] + f[last[j]]) % MOD;
        }
        last[s[i] - 'a'] = i;
    }
    ans = 0;
    for (i = 0; i < 26; i++) {
        if (last[i] != -1) ans = (ans + f[last[i]]) % MOD;
    }
    return ans;
}

题目链接:940. 不同的子序列 II - 力扣(LeetCode)