1. 程式人生 > >Leetcode 940. Distinct Subsequences II

Leetcode 940. Distinct Subsequences II

Problem:

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

 

Solution:

  這道題說白了一點都不難,問題是我沒想到。拿到題目的第一反映是動態規劃,但看到S的長度只有2000,我思路一直限制在了提高維度這一方向上,結果答案只是O(n)的時間複雜度。這裡用了一個last陣列記錄了所有小寫字母結尾的子序列數目,從頭遍歷字串S,在所有子序列後面加上S[i]可以得到新的子序列,然後加上S[i]本身就是以S[i]結尾的新的子序列個數。程式碼非常簡單。

Code:

 

 1 class Solution {
 2 public:
 3     int distinctSubseqII(string S) {
 4         int
m = S.size(); 5 int result = 0; 6 vector<int> last(26,0); 7 for(int i = 0;i != m;++i){ 8 int sum = 0; 9 for(int i = 0;i != 26;++i) 10 sum = (sum+last[i])%1000000007; 11 last[S[i]-'a'] = sum+1; 12 } 13 for(int i = 0;i != 26;++i) 14 result = (result+last[i])%1000000007; 15 return result; 16 } 17 };