Skip to content

Commit 03ccae9

Browse files
authored
Update 140-word-break-ii.js
1 parent 5b5c64a commit 03ccae9

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

140-word-break-ii.js

+32
Original file line numberDiff line numberDiff line change
@@ -57,3 +57,35 @@ const wordBreak = function (s, wordDict) {
5757
const res = dfs(0)
5858
return res.filter((a) => a.join('') === s).map((a) => a.join(' '))
5959
}
60+
61+
// another
62+
63+
/**
64+
* @param {string} s
65+
* @param {string[]} wordDict
66+
* @return {string[]}
67+
*/
68+
69+
const wordBreak = (s, wordDict) => {
70+
const set = new Set(wordDict)
71+
return helper(s, 0, set)
72+
}
73+
74+
function helper(s, idx, dict) {
75+
if(idx === s.length) return []
76+
const res = []
77+
for(let i = idx; i < s.length; i++) {
78+
const tmp = s.slice(idx, i + 1)
79+
if(dict.has(tmp)) {
80+
const arr = helper(s, i + 1, dict)
81+
if(i + 1 >= s.length) {
82+
res.push(tmp)
83+
} else if(arr.length) {
84+
for(let e of arr) {
85+
res.push(tmp + ' ' + e)
86+
}
87+
}
88+
}
89+
}
90+
return res
91+
}

0 commit comments

Comments
 (0)