题目:上一题139的加强版
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。
返回所有这些可能的句子。
我的实现方法是依旧是记忆化回溯,相比上一题加上了句子分割后的拼接。
#!/usr/bin/env python3.6
# _*_coding:utf-8 _*_
# @Time : 2019/10/29 21:10
# @Author : Grey
from typing import List
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
n = len(s)
if n == 0:
return [""]
if n == 1 and s in wordDict:
return [s]
if n == 1 and s not in wordDict:
return []
dic = {}
for word in wordDict:
p = s.find(word)
while p != -1:
if p not in dic.keys():
dic[p] = []
dic[p].append(p+len(word))
p = s.find(word, p+1)
visited = [False for _ in range(n)]
hasAns = [False for _ in range(n)]
ans = [[] for _ in range(n)]
def findBreak(x):
if visited[x]:
return hasAns[x]
if x not in dic.keys():
visited[x] = True
return False
for y in dic[x]:
if y == n:
ans[x].append(s[x:y])
else:
hasAns[y] = findBreak(y)
if hasAns[y]:
ans[x].extend(s[x:y] + " "+ ss for ss in ans[y])
visited[x] = True
hasAns[x] = True
return hasAns[x]
findBreak(0)
return ans[0]

本文介绍了一种使用记忆化回溯算法解决单词拆分II问题的方法,通过在给定的字符串中增加空格来构建由字典中单词组成的句子,并返回所有可能的句子组合。
364

被折叠的 条评论
为什么被折叠?



