-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathword-break-ii.ts
More file actions
30 lines (25 loc) · 886 Bytes
/
Copy pathword-break-ii.ts
File metadata and controls
30 lines (25 loc) · 886 Bytes
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
function wordBreak(s: string, wordDict: string[]): string[] {
const wordSet = new Set(wordDict);
const memo: { [key: string]: string[] } = {};
function backtrack(start: number): string[] {
if (start === s.length) {
return [''];
}
if (memo[start] !== undefined) {
return memo[start];
}
const sentences: string[] = [];
for (let end = start + 1; end <= s.length; end++) {
const word = s.slice(start, end);
if (wordSet.has(word)) {
const restSentences = backtrack(end);
for (const restSentence of restSentences) {
sentences.push(word + (restSentence === '' ? '' : ' ' + restSentence));
}
}
}
memo[start] = sentences;
return sentences;
}
return backtrack(0);
};