AlgoMaster Logo

Distinct Subsequences

Ashish

Ashish Pratap Singh

hard

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Solution

Intuition:

The basic idea is to recursively try to match each character of the string t with the characters in s. At each step, we have two choices: either take the character from s to match with the current character of t or skip the character from s. The base cases are defined when t becomes empty (which means we found a subsequence) or when s becomes empty without fully matching t.

Code:

2. Memoization

Intuition:

The recursive solution contains overlapping subproblems. By storing the results of already computed states (i, j), we can avoid redundant calculations. This transforms the recursion into a top-down dynamic programming approach using a 2D array for memoization.

Code:

3. Tabulation

Intuition:

Using a bottom-up approach, we can fill up a 2D table where dp[i][j] indicates the number of distinct subsequences of t[0...j-1] in s[0...i-1]. We initialize the first row and first column based on the base conditions and progressively fill the DP table.

Code:

4. Optimized Tabulation

Intuition:

Since at every step we only use the current and previous rows, we can optimize space by maintaining only two rows at a time. Swapping rows reduces space complexity from O(m*n) to O(n).

Code: