1. 程式人生 > >Leetcode-940 Distinct Subsequences II(不同的子序列 II)

Leetcode-940 Distinct Subsequences II(不同的子序列 II)

str col 序列 strong return etc cts public har

 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])
22 dp[i]=dp[i-1]*2+1; 23 else 24 dp[i]=dp[i-1]+dp[i-1]-dp[last[i]-1]; 25 if(dp[i]<0) 26 dp[i]+=mod; 27 dp[i]%=mod; 28 } 29 return dp[n]; 30 } 31 };

代碼借鑒:https://blog.csdn.net/icefox_zhx/article/details/77254400

Leetcode-940 Distinct Subsequences II(不同的子序列 II)