Distinct Subsequences LeetCode Solution

Last updated on October 9th, 2024 at 05:56 pm

Here, We see Distinct Subsequences LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.

List of all LeetCode Solution

Topics

Dynamic Programming, String

Companies

Yelp

Level of Question

Hard

Distinct Subsequences LeetCode Solution

Distinct Subsequences LeetCode Solution

Problem Statement

Given two strings s and t, return the number of distinct subsequences of s which equals t.

The test cases are generated so that the answer fits on a 32-bit signed integer.

Example 1:
Input: s = “rabbbit”, t = “rabbit”
Output: 3
Explanation: As shown below, there are 3 ways you can generate “rabbit” from s.
rabbbit
rabbbit
rabbbit

1. Distinct Subsequences LeetCode Solution C++

class Solution {
public:
    int numDistinct(string s, string t) {
        int m = t.length(), n = s.length();
        vector<vector<int>> dp(m + 1, vector<int> (n + 1, 0));
        for (int j = 0; j <= n; j++) dp[0][j] = 1;
        for (int j = 1; j <= n; j++)
            for (int i = 1; i <= m; i++)
                dp[i][j] = dp[i][j - 1] + (t[i - 1] == s[j - 1] ? dp[i - 1][j - 1] : 0);
        return dp[m][n];
    }
};  

2. Distinct Subsequences LeetCode Solution Java

class Solution {
public int numDistinct(String s, String t) {
    int[][] mem = new int[t.length()+1][s.length()+1];
    for(int j=0; j<=s.length(); j++) {
        mem[0][j] = 1;
    }
    for(int i=0; i<t.length(); i++) {
        for(int j=0; j<s.length(); j++) {
            if(t.charAt(i) == s.charAt(j)) {
                mem[i+1][j+1] = mem[i][j] + mem[i+1][j];
            } else {
                mem[i+1][j+1] = mem[i+1][j];
            }
        }
    }
    return mem[t.length()][s.length()];
}
}

3. Distinct Subsequences Solution JavaScript

var numDistinct = function (s, t) {
    if (s.length < t.length) return 0;
    [s, t] = [t, s];
    let m = s.length;
    let n = t.length;
    let aa = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
    for (let j = 0; j <= n; j++) {
        aa[0][j] = 1;
    }
    for (let i = 1; i <= m; i++)
        for (let j = 1; j <= n; j++)
            if (s[i - 1] === t[j - 1]) {
                aa[i][j] = aa[i][j - 1] + aa[i - 1][j - 1];
            } else {
                aa[i][j] = aa[i][j - 1];
            }
    return aa[m][n];
};

4. Distinct Subsequences Solution Python

class Solution(object):
    def numDistinct(self, s, t):
        dp = [[0] * (len(s) + 1) for _ in range(len(t) + 1)]
        for col in range(len(dp[0])):
            dp[0][col] = 1
        for x in range(1, len(s) + 1):
            for y in range(1, len(t) + 1):
                if s[x - 1] == t[y - 1]:
                    dp[y][x] = dp[y - 1][x - 1] + dp[y][x - 1]
                else:
                    dp[y][x] = dp[y][x - 1]
        return dp[-1][-1]
Scroll to Top