1239. Word Break II — All Sentence Splits

HardDynamic ProgrammingString DP

Given a string s and a dictionary wordDict, add spaces to s to build every sentence where each word is in the dictionary (words may be reused). Return all such sentences in ascending lexicographic order. The input is JSON {s, wordDict}.

Input: JSON {s, wordDict}.

Output: Array — all valid sentences, sorted ascending.

Examples

Example 1
Input: {"s":"catsanddog","wordDict":["cat","cats","and","sand","dog"]}
Output: ["cat sand dog","cats and dog"]
Explanation: Two valid segmentations.
Example 2
Input: {"s":"catsandog","wordDict":["cats","dog","sand","and","cat"]}
Output: []
Explanation: No valid segmentation.
Example 3
Input: {"s":"aa","wordDict":["a"]}
Output: ["a a"]
Explanation: Reuse the dictionary word.

Constraints

Asked by

AmazonGoogleMicrosoftMetaAdobe
Solve this problem in the editor →