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:

  1. S contains only lowercase letters.
  2. 1 <= S.length <= 2000

 

Approach #1: Math. [Java]

class Solution {
    public int distinctSubseqII(String S) {
        long end[] = new long[26], mod = (long)1e9 + 7;
        for (char c : S.toCharArray())
            end[c - 'a'] = Arrays.stream(end).sum()%mod + 1;
        return (int)(Arrays.stream(end).sum()%mod);
    }
}

  

Analysis:

 

 

Reference:

https://www.jianshu.com/p/02501f516437

 

posted @ 2019-03-27 22:34  Veritas_des_Liberty  阅读(265)  评论(0编辑  收藏  举报