582. 单词拆分II
中文
English
给一字串s和单词的字典dict,在字串中增加空格来构建一个句子,并且所有单词都来自字典。
返回所有有可能的句子。
样例
样例 1:
输入:"lintcode",["de","ding","co","code","lint"]
输出:["lint code", "lint co de"]
解释:
插入一个空格是"lint code",插入两个空格是 "lint co de"
样例 2:
输入:"a",[]
输出:[]
解释:字典为空
class Solution:
"""
@param: s: A string
@param: wordDict: A set of words.
@return: All possible sentences.
"""
def wordBreak(self, s, wordDict):
# write your code here
if not s:
return []
cache = {}
def dfs(s):
if not s:
return [[]]
if s in cache:
return cache[s]
ans = []
for i in range(len(s)):
word = s[0:i+1]
if word in wordDict:
words = dfs(s[i+1:])
for p in words:
ans.append([word] + p)
cache[s] = ans
return ans
ans = [" ".join(l) for l in dfs(s)]
return ans
超时的例子:
class Solution:
"""
@param: s: A string
@param: wordDict: A set of words.
@return: All possible sentences.
"""
def wordBreak(self, s, wordDict):
# write your code here
def get_words_matrix(s):
n = len(s)
ans = collections.defaultdict(list)
for i in range(n):
for j in range(i, n):
if s[i:j+1] in wordDict:
ans[i].append(j)
return ans
if not s:
return []
ans = []
dp = get_words_matrix(s)
def dfs(s, start, path):
if start == len(s):
ans.append(" ".join(path))
return
for pos in dp[start]:
path.append(s[start:pos+1])
dfs(s, pos+1, path)
path.pop()
dfs(s, start=0, path=[])
return ans
输入
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
["a","aa","aaa","aaaa","aaaaa","aaaaaa","aaaaaaa","aaaaaaaa","aaaaaaaaa","aaaaaaaaaa"]