Skip to content

Commit 5ce9854

Browse files
authored
Update 140-word-break-ii.js
1 parent 629eae4 commit 5ce9854

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

140-word-break-ii.js

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,3 +24,36 @@ function backTrack(s, wordDict, mem) {
2424
mem[s] = result
2525
return result
2626
}
27+
28+
// another
29+
30+
/**
31+
* @param {string} s
32+
* @param {string[]} wordDict
33+
* @return {string[]}
34+
*/
35+
const wordBreak = function (s, wordDict) {
36+
const dictSet = new Set(wordDict)
37+
const memo = {}
38+
function dfs(start) {
39+
if (start > s.length - 1) {
40+
return [[]]
41+
}
42+
if (memo[start] !== undefined) {
43+
return memo[start]
44+
}
45+
const out = []
46+
for (let i = start; i < s.length; i++) {
47+
const substr = s.substring(start, i + 1)
48+
if (dictSet.has(substr)) {
49+
let next = dfs(i + 1)
50+
for (let n of next) {
51+
out.push([substr, ...n])
52+
}
53+
}
54+
}
55+
return (memo[start] = out)
56+
}
57+
const res = dfs(0)
58+
return res.filter((a) => a.join('') === s).map((a) => a.join(' '))
59+
}

0 commit comments

Comments
 (0)