-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path140. Word Break II.js
40 lines (35 loc) · 959 Bytes
/
140. Word Break II.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
/**
* @param {string} s
* @param {string[]} wordDict
* @return {string[]}
*/
var wordBreak = function (s, wordDict) {
const answer = [];
const dp = Array.from({ length: s.length + 1 }, () => false);
dp[s.length] = true;
for (let i = s.length - 1; i >= 0; i--) {
for (const word of wordDict) {
if (i + word.length <= s.length && s.slice(i, i + word.length) === word) {
if (!dp[i]) {
dp[i] = [[word, i + word.length]];
} else {
dp[i].push([word, i + word.length]);
}
}
}
}
const recursive = (wordArray, currentIndex, currentDp) => {
if (currentIndex > s.length || !currentDp) {
return;
}
if (currentIndex === s.length) {
answer.push(wordArray.join(" "));
} else {
for (const [word, nextIndex] of currentDp) {
recursive([...wordArray, word], nextIndex, dp[nextIndex]);
}
}
};
recursive([], 0, dp[0]);
return answer;
};