Distinct Subsequences leetcode solution

Distinct Subsequences leetcode solution

Distinct Subsequences leetcode solution

Given a string S and a string T, count the number of distinct subsequences of T in S.

A subsequence of a string is a new string which is formed from the original string by deleting some (can be none) of the characters without disturbing
the relative positions of the remaining characters. (ie, “ACE” is a subsequence of “ABCDE” while “AEC” is not).

Here is an example:
S = “rabbbit”, T = “rabbit”

Return 3.

Distinct Subsequences leetcode solution

int numDistinct(string S, string T) {
 int M = S.length();
 int N = T.length();
 if(M==0 || N==0)
 return 0 ;
 vector<int> v2(N+1, 99);
 vector < vector<int> > num(M+1,v2);
 for (int i = 0; i <= N; i++)
 num[0][i] = 0;
 for (int i = 0; i <= M; i++)
 num[i][0] = 1;
 for (int i = 1; i <= M; i++) {
 for (int j = 1; j <= N; j++) {
 if (S[i - 1] != T[j - 1]) {
 num[i][j] = num[i - 1][j];
 } else {
 num[i][j] = num[i - 1][j] + num[i - 1][j - 1];
 return num[M][N];

Resolving technical problems:

Solve your technical problems instantly

We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM

Mail your problem details at writeulearn@gmail.com along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.