Skip to content

Commit 7395d01

Browse files
committed
Add solution #140
1 parent 0229153 commit 7395d01

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

README.md

+1
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@
9090
137|[Single Number II](./0137-single-number-ii.js)|Medium|
9191
138|[Copy List with Random Pointer](./0138-copy-list-with-random-pointer.js)|Medium|
9292
139|[Word Break](./0139-word-break.js)|Medium|
93+
140|[Word Break II](./0140-word-break-ii.js)|Hard|
9394
141|[Linked List Cycle](./0141-linked-list-cycle.js)|Easy|
9495
142|[Linked List Cycle II](./0142-linked-list-cycle-ii.js)|Medium|
9596
143|[Reorder List](./0143-reorder-list.js)|Medium|

solutions/0140-word-break-ii.js

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
/**
2+
* 140. Word Break II
3+
* https://leetcode.com/problems/word-break-ii/
4+
* Difficulty: Hard
5+
*
6+
* Given a string s and a dictionary of strings wordDict, add spaces in s to
7+
* construct a sentence where each word is a valid dictionary word. Return
8+
* all such possible sentences in any order.
9+
*
10+
* Note that the same word in the dictionary may be reused multiple times in
11+
* the segmentation.
12+
*/
13+
14+
/**
15+
* @param {string} s
16+
* @param {string[]} wordDict
17+
* @return {string[]}
18+
*/
19+
var wordBreak = function(s, wordDict) {
20+
const result = [];
21+
backtrack(result, s, wordDict, '');
22+
return result;
23+
};
24+
25+
function backtrack(result, s, wordDict, substr) {
26+
if (!s.length) {
27+
result.push(substr);
28+
return;
29+
}
30+
31+
wordDict.forEach(word => {
32+
if (s.length >= word.length && word === s.substring(0, word.length)) {
33+
backtrack(
34+
result,
35+
s.substring(word.length),
36+
wordDict,
37+
substr.length ? `${substr} ${word}` : word,
38+
);
39+
}
40+
});
41+
}

0 commit comments

Comments
 (0)