Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
Given two strings s
and t
, return the number of distinct subsequences of s
which equals t
.
A string’s subsequence is a new string formed from the original string by deleting some (can be none) of the characters without disturbing the remaining characters’ relative positions. (i.e., "ACE"
is a subsequence of "ABCDE"
while "AEC"
is not).
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
Example 2:
Input: s = "babgbag", t = "bag"
Output: 5
Explanation:
As shown below, there are 5 ways you can generate "bag" from S.
babgbag
babgbag
babgbag
babgbag
babgbag
Constraints:
1 <= s.length, t.length <= 1000
s
and t
consist of English letters.public int numDistinct(String S, String T) {
// array creation
int[][] mem = new int[T.length()+1][S.length()+1];
// filling the first row: with 1s
for(int j=0; j<=S.length(); j++) {
mem[0][j] = 1;
}
// the first column is 0 by default in every other rows but the first, which we need.
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()];
}
class Solution {
public:
int numDistinct(string s, string t) {
int m = t.length(), n = s.length();
vector<int> cur(m + 1, 0);
cur[0] = 1;
for (int j = 1; j <= n; j++) {
int pre = 1;
for (int i = 1; i <= m; i++) {
int temp = cur[i];
cur[i] = cur[i] + (t[i - 1] == s[j - 1] ? pre : 0);
pre = temp;
}
}
return cur[m];
}
};
class Solution:
def numDistinct(self, s, t):
@lru_cache(None)
def dp(i, j):
if i == -1: return j == -1
if j == -1: return j == -1
return dp(i-1, j) + (s[i] == t[j]) * dp(i-1, j-1)
return dp(len(s) - 1, len(t) - 1)
In our experience, we suggest you solve this Distinct Subsequences LeetCode Solution and gain some new skills from Professionals completely free and we assure you will be worth it.
If you are stuck anywhere between any coding problem, just visit Queslers to get the Distinct Subsequences LeetCode Solution
I hope this Distinct Subsequences LeetCode Solution would be useful for you to learn something new from this problem. If it helped you then don’t forget to bookmark our site for more Coding Solutions.
This Problem is intended for audiences of all experiences who are interested in learning about Data Science in a business context; there are no prerequisites.
Keep Learning!
More Coding Solutions >>