Word break II (all sentences)
Hard TimeO(n²·k) SpaceO(n·k)
Given a string s and a dictionary words, return every sentence s can be broken into, rather than merely whether one exists. Every character must be used and every piece must be a dictionary word, words may be reused any number of times, and a string with no valid break returns an empty list.
Examples
Example 1
- Input
- s = "catsanddog"dictionary = ["cat", "cats", "and", "sand", "dog"]
- Output
["cat sand dog","cats and dog"]cat sand dogandcats and dog: both use every character, and every piece is a word.
Example 2
- Input
- s = "catsandog"dictionary = ["cats", "dog", "sand", "and", "cat"]
- Output
- Every way of starting leaves
[]ogat the end, which is not a word, so no sentence exists.
The Code
function wordBreakAll(s, dictionary) {
const memo = {};
function solve(start) {
if (start === s.length) return [""];
if (memo[start] !== undefined) return memo[start];
const results = [];
for (let end = start + 1; end <= s.length; end++) {
const piece = s.slice(start, end);
if (dictionary.indexOf(piece) === -1) continue;
const rest = solve(end);
for (let i = 0; i < rest.length; i++) {
results.push(rest[i] === "" ? piece : piece + " " + rest[i]);
}
}
memo[start] = results;
return results;
}
return solve(0);
}
wordBreakAll("catsanddog", ["cat", "cats", "and", "sand", "dog"]);Done
The first 31 calls, of 47. This one does not fit on a page.
More like this
All dynamic programming examples (20) →- Climbing stairs Count the ways to the top — Fibonacci in disguise.
- Coin change Try every coin and keep the cheapest way to make the amount.
- Max subarray One pass, two running totals — Kadane’s algorithm.
- LCS Match a character or drop one from either string.
- Edit distance Insert, delete, or replace — take the cheapest at each mismatch.
- 0/1 Knapsack For each item, take it or leave it — keep the more valuable branch.