-
Notifications
You must be signed in to change notification settings - Fork 128
/
Distinct Subsequences.js
103 lines (83 loc) · 2.13 KB
/
Distinct Subsequences.js
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
/**
Given a string S and a string T, count the number of distinct subsequences of T in S.
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).
Here is an example:
S = "rabbbit", T = "rabbit"
Return 3.
*/
/**
* @param {string} s
* @param {string} t
* @return {number}
*
* S[j-1]!= T[i-1]:DP[i][j] = DP[i][j-1]
* S[j-1]==T[i-1]:DP[i][j] = DP[i-1][j-1] + DP[i][j-1]
*/
var numDistinct = function(s, t) {
var lenS = s.length,
lenT = t.length,
i,
j,
dp;
if (lenS < lenT) {
return 0;
}
if (lenS === lenT) {
return s === t? 1 : 0;
}
dp = [];
for (i = 0; i <= lenT; i++) {
dp.push(new Array(lenS + 1));
for (j = 0; j <= lenS; j++) {
dp[i][j] = 0;
}
}
for (j = 0; j <= lenS; j++) {
dp[0][j] = 1;
}
for (i = 0; i < lenT; i++) {
for (j = 0; j < lenS; j++) {
dp[i + 1][j + 1] = dp[i + 1][j];
if (s.charAt(j) === t.charAt(i)) {
dp[i + 1][j + 1] += dp[i][j];
}
}
}
return dp[lenT][lenS];
};
// use 1D dp solution
// draw 2D dp realation and try to save space
/**
* @param {string} s
* @param {string} t
* @return {number}
*
* S[j-1]!= T[i-1]:DP[i][j] = DP[i][j-1]
* S[j-1]==T[i-1]:DP[i][j] = DP[i-1][j-1] + DP[i][j-1]
*/
var numDistinct = function(s, t) {
var lenS = s.length,
lenT = t.length,
i,
j,
dp;
if (lenS < lenT) {
return 0;
}
if (lenS === lenT) {
return s === t? 1 : 0;
}
dp = [];
dp[0] = 1;
for (i = 1; i <= lenT; i++) {
dp[i] = 0;
}
for (j = 0; j <= lenS; j++) {
for (i = lenT - 1; i >= 0; i--) {
if (s.charAt(j) === t.charAt(i)) {
dp[i + 1] += dp[i];
}
}
}
return dp[lenT];
};