Distinct Subsequences II in C++


Suppose we have a string S, we have to count the number of distinct subsequences of S. The result can be large, so we will return the answer modulo 10^9 + 7.

So, if the input is like "bab", then the output will be 6, as there are 6 different sequences, these are "a", "b, "ba", "ab", "bb", "abb".

To solve this, we will follow these steps −

  • Define a function add(), this will take a, b,

  • return ((a mod MOD) + (b mod MOD)) mod MOD

  • Define a function sub(), this will take a, b,

  • return (((a mod MOD) - (b mod MOD)) + MOD) mod MOD

  • Define a function mul(), this will take a, b,

  • return ((a mod MOD) * (b mod MOD)) mod MOD

  • From the main method, so the following −

  • n := size of s

  • Define an array dp of size 26

  • res := 0

  • s := concatenate space before s

  • for initialize i := 1, when i <= n, update (increase i by 1), do −

    • x := s[i]

    • added := sub(add(res, 1), dp[x - 'a'])

    • dp[x - 'a'] = add(dp[x - 'a'], added)

    • res := add(res, added)

  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
const lli MOD = 1e9 + 7;
class Solution {
   public:
   lli add(lli a, lli b){
      return ( (a % MOD) + (b % MOD) ) % MOD;
   }
   lli sub(lli a, lli b){
      return ( ( (a % MOD) - (b % MOD) ) + MOD ) % MOD;
   }
   lli mul(lli a, lli b){
      return ( (a % MOD) * (b % MOD) ) % MOD;
   }
   int distinctSubseqII(string s) {
      int n = s.size();
      vector <lli> dp(26);
      int res = 0;
      s = " " + s;
      for(lli i = 1; i <= n; i++){
         char x = s[i];
         int added = sub(add(res, 1) , dp[x - 'a']);
         dp[x - 'a'] = add(dp[x - 'a'], added);
         res = add(res, added);
      }
      return res;
   }
};
main(){
   Solution ob;
   cout << (ob.distinctSubseqII("bab"));
}

Input

"bab"

Output

6

Updated on: 04-Jun-2020

70 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements