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".
思路:这在LeetCode里面已经算是难题了,主要是考察思维的灵活性。
手推样例可以发现,dp[i] = 2*dp[i-1] 因为最好的情况是新加的字母与之前的每一个都构成子串。
但是还要去重,因为会有重复的元素出现,所以利用last[]记录相同字母最近一次出现的位置,减去即可。
dp [i+1]= dp[i]*2-dp[last[x]]
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
class Solution {
public:
int distinctSubseqII(string S) {
int n= S.size();
ll dp[20005];
memset(dp,0,sizeof(dp));
int mod=1e9+7;
int last[26];
memset(last,-1,sizeof(last));
dp[0]=1;
//last[0]=-1;
for(int i=0;i<n;i++)
{
dp[i+1]=dp[i]*2%mod;
int x= S[i]-'a';
if(last[x]>=0)
{
dp[i+1]=(dp[i+1]-dp[last[x]]+mod)%mod;
}
last[x]=i;
}
dp[n]=(dp[n]-1)%mod;
return dp[n];
}
};