- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Distinct Subsequences in C++

Suppose we have strings S and T. We have to count number of distinct sequences of S which is equal to T.

We know that a subsequence of a string is a new string which is formed from the original string by removing some (can be none) of the characters without disturbing the relative positions of the remaining characters. (Like, "ACE" is a subsequence of "ABCDE" while "AEC" is not).

If the input strings are “baalllloonnn” and “balloon”, then there will be 36 different ways to select.

To solve this, we will follow these steps −

n := size of s, m := size of t. Update s and t by concatenating blank spaces before them

Make one matrix of size (n + 1) x (m + 1)

set dp[0, 0] := 1, then set 1 for 0th column of all row, put 1

for i in range 1 to n

for j in range 1 to m

if s[i] = t[j], then

dp[i, j] := dp[i – 1, j – 1]

dp[i, j] := dp[i, j] + dp[i – 1, j]

return dp[n, m]

## Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h> using namespace std; typedef long long int lli; class Solution { public: int numDistinct(string s, string t) { int n = s.size(); int m = t.size(); s = " " + s; t = " " + t; vector < vector <lli>> dp(n + 1, vector <lli> (m + 1)); dp[0][0] = 1; for(int i = 1; i<= n; i++)dp[i][0] = 1; for(int i = 1; i <= n; i++){ for(int j = 1; j <= m; j++){ if(s[i] == t[j]) dp[i][j] = dp[i - 1][j - 1]; dp[i][j]+= dp[i - 1][j]; } } return dp[n][m]; } }; main(){ Solution ob; cout << (ob.numDistinct("baalllloonnn", "balloon")); }

## Input

"baalllloonnn" "balloon"

## Output

36

- Related Questions & Answers
- Distinct Subsequences II in C++
- Distinct Subsequences in C++ Programming
- Count of subsequences having maximum distinct elements in C++
- Program to find number of distinct subsequences in Python
- Increasing Subsequences in C++
- Count all increasing subsequences in C++
- Number of Matching Subsequences in C++
- Powers of two and subsequences in C++
- Split Array into Consecutive Subsequences in C++
- Print all subsequences of a string in C++
- Distinct Echo Substrings in C++
- C# Linq Distinct() Method
- Print all subsequences of a string using ArrayList in C++
- Count all subsequences having product less than K in C++
- Count of AP (Arithmetic Progression) Subsequences in an array in C++