Skip to content

Commit e027efc

Browse files
committed
Added 2D DP JS solution for problem 115
1 parent 7dc5a3a commit e027efc

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

javascript/115-Distinct-Subsequences.js

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,3 +27,38 @@ function numDistinct(s, t) {
2727

2828
return cache[0];
2929
}
30+
31+
/**
32+
* @param {string} s
33+
* @param {string} t
34+
* @return {number}
35+
*/
36+
function numDistinct(s, t) {
37+
38+
const sLen = s.length;
39+
const tLen = t.length;
40+
41+
if (sLen < tLen) {
42+
return 0;
43+
}
44+
45+
const cache = new Array(sLen + 1).fill()
46+
.map(() => new Array(tLen + 1));
47+
48+
cache[sLen].fill(0);
49+
for (let r = 0; r <= sLen; ++r) {
50+
cache[r][tLen] = 1;
51+
}
52+
53+
for (let r = sLen - 1; r >= 0; --r) {
54+
for (let c = tLen - 1; c >= 0; --c) {
55+
cache[r][c] = cache[r + 1][c] + (
56+
s[r] === t[c]
57+
? cache[r + 1][c + 1]
58+
: 0
59+
);
60+
}
61+
}
62+
63+
return cache[0][0];
64+
}

0 commit comments

Comments
 (0)