1. 程式人生 > >LeetCode 940. Distinct Subsequences II(遞推找規律)

LeetCode 940. Distinct Subsequences II(遞推找規律)

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