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 };

猜你喜欢

转载自www.cnblogs.com/haoweizh/p/10242317.html
今日推荐