|
| 1 | +# 140. Word Break II |
| 2 | +Given a string `s` and a dictionary of strings `wordDict`, add spaces in `s` to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in **any order**. |
| 3 | + |
| 4 | +**Note** that the same word in the dictionary may be reused multiple times in the segmentation. |
| 5 | + |
| 6 | +#### Example 1: |
| 7 | +<pre> |
| 8 | +<strong>Input:</strong> s = "catsanddog", wordDict = ["cat","cats","and","sand","dog"] |
| 9 | +<strong>Output:</strong> ["cats and dog","cat sand dog"] |
| 10 | +</pre> |
| 11 | + |
| 12 | +#### Example 2: |
| 13 | +<pre> |
| 14 | +<strong>Input:</strong> s = "pineapplepenapple", wordDict = ["apple","pen","applepen","pine","pineapple"] |
| 15 | +<strong>Output:</strong> ["pine apple pen apple","pineapple pen apple","pine applepen apple"] |
| 16 | +<strong>Explanation:</strong> Note that you are allowed to reuse a dictionary word. |
| 17 | +</pre> |
| 18 | + |
| 19 | +#### Example 3: |
| 20 | +<pre> |
| 21 | +<strong>Input:</strong> s = "catsandog", wordDict = ["cats","dog","sand","and","cat"] |
| 22 | +<strong>Output:</strong> [] |
| 23 | +</pre> |
| 24 | + |
| 25 | +#### Constraints: |
| 26 | +* `1 <= s.length <= 20` |
| 27 | +* `1 <= wordDict.length <= 1000` |
| 28 | +* `1 <= wordDict[i].length <= 10` |
| 29 | +* `s` and `wordDict[i]` consist of only lowercase English letters. |
| 30 | +* All the strings of `wordDict` are **unique**. |
| 31 | +* Input is generated in a way that the length of the answer doesn't exceed 10<sup>5</sup>. |
| 32 | + |
| 33 | +## Solutions (Python) |
| 34 | + |
| 35 | +### 1. Solution |
| 36 | +```Python |
| 37 | +from functools import cache |
| 38 | + |
| 39 | + |
| 40 | +class Solution: |
| 41 | + def wordBreak(self, s: str, wordDict: List[str]) -> List[str]: |
| 42 | + words = set(wordDict) |
| 43 | + |
| 44 | + @cache |
| 45 | + def backtracking(s: str) -> Optional[List[str]]: |
| 46 | + ret = [] |
| 47 | + |
| 48 | + for i in range(1, min(len(s) + 1, 10)): |
| 49 | + if s[:i] in wordDict: |
| 50 | + if i == len(s): |
| 51 | + return ret + [s] |
| 52 | + sentences = backtracking(s[i:]) |
| 53 | + if sentences is not None: |
| 54 | + ret.extend("{} {}".format(s[:i], sentence) |
| 55 | + for sentence in sentences) |
| 56 | + |
| 57 | + return ret if ret != [] else None |
| 58 | + |
| 59 | + return backtracking(s) if backtracking(s) is not None else [] |
| 60 | +``` |
0 commit comments