-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy path0140-word-break-ii.js
41 lines (38 loc) · 976 Bytes
/
0140-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
41
/**
* 140. Word Break II
* https://leetcode.com/problems/word-break-ii/
* Difficulty: Hard
*
* Given a string s and a dictionary of strings wordDict, add spaces in s to
* construct a sentence where each word is a valid dictionary word. Return
* all such possible sentences in any order.
*
* Note that the same word in the dictionary may be reused multiple times in
* the segmentation.
*/
/**
* @param {string} s
* @param {string[]} wordDict
* @return {string[]}
*/
var wordBreak = function(s, wordDict) {
const result = [];
backtrack(result, s, wordDict, '');
return result;
};
function backtrack(result, s, wordDict, substr) {
if (!s.length) {
result.push(substr);
return;
}
wordDict.forEach(word => {
if (s.length >= word.length && word === s.substring(0, word.length)) {
backtrack(
result,
s.substring(word.length),
wordDict,
substr.length ? `${substr} ${word}` : word,
);
}
});
}