1 class Solution 2 { 3 public: 4 int distinctSubseqII(string S) 5 { 6 int n = S.size(); 7 int mod = 1000000007; 8 int h[2002],last[2002],dp[2002]; 9 char a[2002]; 10 memset(h,0,sizeof(h)); 11 memset(last,0,sizeof(last)); 12 memset(dp,0,sizeof(dp)); 13 for(int i=1; i<=n; ++i) 14 { 15 a[i]=S[i-1]; 16 last[i]=h[a[i]]; 17 h[a[i]]=i; 18 } 19 for(int i=1; i<=n; ++i) 20 { 21 if(!last[i]) dp[i]=dp[i-1]*2+1; 22 else dp[i]=dp[i-1]+dp[i-1]-dp[last[i]-1]; 23 if(dp[i]<0) dp[i]+=mod; 24 dp[i]%=mod; 25 } 26 return dp[n]; 27 } 28 };