Distinct Subsequences
Distinct Subsequences
Dynamic Programming
Problem Statement
Given two strings s
and t
, return the number of distinct subsequences of s
which equals t
.
Example
Example 1:
s:rabbbit
t:rabbit
Distinct Subsequences:3
r a b b _ i t
r a b _ b i t
r _ a b b i t
Solution
This is another 2D dynamic programming problem. We'll create a DP grid, dp
, of size (m+1) x (n+1)
, where m
and n
are the lengths of strings s
and t
. dp[i][j]
will represent the number of distinct subsequences of s[0...i-1]
which equals t[0...j-1]
.
The recurrence relation is as follows: If s[i-1] == t[j-1]
, then dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
. Otherwise, dp[i][j] = dp[i-1][j]
.
Algorithm Steps (DP)
- Create a DP grid of size
(m+1) x (n+1)
. - Initialize the first column to 1s, as an empty string is a subsequence of any string.
- Iterate through the grid from
(1, 1)
to(m, n)
. - If
s[i-1] == t[j-1]
,dp[i][j] = dp[i-1][j-1] + dp[i-1][j]
. - Otherwise,
dp[i][j] = dp[i-1][j]
. - The final answer is
dp[m][n]
.
#
r
a
b
b
i
t
Step: 1 / 44
Distinct Subsequences Solution