forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0115-distinct-subsequences.cpp
41 lines (36 loc) · 1.04 KB
/
0115-distinct-subsequences.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
Given 2 strings s & t:
Return # of distinct subsequences of s which equals t
Ex. s = "rabbbit", t = "rabbit" -> 3, RABBbIT, RAbBBIT, RABbBIT
DFS + memo, cache on i & j indices to the # of distinct subseq
2 choices: if chars equal, look at remainder of both s & t
if chars not equal, only look at remainder of s
Time: O(m x n)
Space: O(m x n)
*/
class Solution {
public:
int numDistinct(string s, string t) {
return dfs(s, t, 0, 0);
}
private:
// {(i, j) -> # of distinct subsequences}
map<pair<int, int>, int> dp;
int dfs(string& s, string& t, int i, int j) {
if (j == t.size()) {
return 1;
}
if (i == s.size()) {
return 0;
}
if (dp.find({i, j}) != dp.end()) {
return dp[{i, j}];
}
if (s[i] == t[j]) {
dp[{i, j}] = dfs(s, t, i + 1, j + 1) + dfs(s, t, i + 1, j);
} else {
dp[{i, j}] = dfs(s, t, i + 1, j);
}
return dp[{i, j}];
}
};