题目
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。
链接:https://leetcode.com/problems/word-break-ii/
Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.
Note:
- The same word in the dictionary may be reused multiple times in the segmentation.
- You may assume the dictionary does not contain duplicate words.
Example:
Input:
s = “catsanddog”
wordDict = [“cat”, “cats”, “and”, “sand”, “dog”]
Output:
[
“cats and dog”,
“cat sand dog”
]
思路及代码
DP
- 递归逆序查找
- 思路借鉴于https://zxi.mytechroad.com/blog/leetcode/leetcode-140-word-break-ii/
- set的查询效率大大高于list:set > dict >> list
- 从leetcode评论区看到特殊的test case会导致超时:
- “aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa”
[“a”,“aa”,“aaa”,“aaaa”,“aaaaa”,“aaaaaa”,“aaaaaaa”,“aaaaaaaa”,“aaaaaaaaa”,“aaaaaaaaaa”, “b”]
- “aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa”
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
memo = {}
words = set(wordDict)
def wb(s):
if s in memo:
return memo[s]
ans = []
if s in words:
ans.append(s)
for i in range(1, len(s)):
right = s[i:]
if right not in words:
continue
for w in wb(s[0:i]):
ans += [w + " " + right]
memo[s] = ans.copy()
return memo[s]
return wb(s)
复杂度
T =
O
(
2
n
)
O(2^n)
O(2n)
S =
O
(
2
n
)
O(2^n)
O(2n)