Problem
Given a string S and a string T, count the number of distinct subsequences of S which equals T.
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).
Example 1:
1 |
|
Example 2:
1 |
|
Explanation
-
We can use dynamic programming to solve this problem.
-
Dynamic state is a two dimensional array
dp[i][j]
which represents aS
is choosing characters from the beginning toj
inclusive (top row), andT
is choosing characters from the beginning toi
inclusive (left column), the value ofdp[i][j]
is their result. -
Dynamic init is, when both
T
andS
are empty, the result will be 1 because emptyS
can form emptyT
. Also actually in the top row all elements are 1 because whenT
is empty, no matte how many characters we choose fromS
, they can all form the empty string by choosing the empty string. On the other hand, whenS
is empty, butT
is not empty, thenS
cannot formT
, so left most column values are 0. -
Dynamic function can have two cases. First, if the last characters of
T
andS
are the same, thendp[i][j] = dp[i-1][j-1] + dp[i][j-1]
because if we don’t choose the last characters fromT
andS
then it’s equal todp[i-1][j-1]
, and if we don’t choose the last character fromS
, then it’s equal todp[i][j-1]
. Second case is when the last character are not the same, so we can only don’t choose the last character fromS
, so we havedp[i][j] = dp[i][j-1]
. -
Dynamic result is choosing all characters from
S
andT
, which is the bottom right result.
Solution
1 |
|