Skip to content

Commit 1f22ecc

Browse files
committed
https://leetcode.cn/problems/word-break-ii/
1 parent d4d1177 commit 1f22ecc

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,8 @@ leetcode 测试
1010

1111
##### 包含的内容如下
1212

13+
https://leetcode.cn/problems/word-break-ii/
14+
1315
https://leetcode.cn/problems/word-break/
1416

1517
https://leetcode.cn/problems/binary-tree-maximum-path-sum/

word-break-ii/index.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
export default function wordBreak(s: string, wordDict: string[]): string[] {
2+
if (
3+
Array.from(new Set(s)).some((c) => !wordDict.some((w) => w.includes(c)))
4+
) return [];
5+
const lens = Array.from(new Set(wordDict.map((a) => a.length))).sort((
6+
a,
7+
b,
8+
) => a - b);
9+
const n: number = s.length;
10+
const set: Set<string> = new Set(wordDict);
11+
const cache: string[][][] = Array(n);
12+
const list = dfs(0);
13+
return list.map((t) => t.join(" "));
14+
15+
function dfs(k: number): string[][] {
16+
if (cache[k]) return cache[k];
17+
if (k >= n) return [[]];
18+
const res: string[][] = [];
19+
for (const len of lens) {
20+
const i = k + len;
21+
if (k + len > s.length) break;
22+
const str = s.slice(k, i);
23+
if (set.has(str)) {
24+
const arr = dfs(i);
25+
for (const a of arr) {
26+
res.push([str, ...a]);
27+
}
28+
}
29+
}
30+
cache[k] = res;
31+
return res;
32+
}
33+
}

0 commit comments

Comments
 (0)