题目:
给定一个非空字符串 s 和一个包含非空单词列表的字典 wordDict,在字符串中增加空格来构建一个句子,使得句子中所有的单词都在词典中。返回所有这些可能的句子。
说明:
分隔时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:
输入:
s = “catsanddog”
wordDict = [“cat”, “cats”, “and”, “sand”, “dog”]
输出:
[
“cats and dog”,
“cat sand dog”
]
示例 2:
输入:
s = “pineapplepenapple”
wordDict = [“apple”, “pen”, “applepen”, “pine”, “pineapple”]
输出:
[
“pine apple pen apple”,
“pineapple pen apple”,
“pine applepen apple”
]
解释: 注意你可以重复使用字典中的单词。
示例 3:
输入:
s = “catsandog”
wordDict = [“cats”, “dog”, “sand”, “and”, “cat”]
输出:
[]
思路:回溯。
普通的回溯超时,需要剪枝。
超时来自重复计算,例如,backTrack(2)
在backTrack(1)
的时候可能已经算过了,又在从2
开始的回溯再算了一遍。
所以,我们要记录,若从某个位置j
切分递归后无法得到完整的切分,之后的回溯就跳过该位置。用数组memo[i]
来记录以位置i
结尾的的子串是否可以继续划分。
回溯函数传入当前开始切割的位置pos
,如果判断从pos
开始无法切割,说明以pos-1
结尾的字符串就不用往下回溯了,所以将memo[pos-1]
置为False
。
如何判断当前无法正确切割?在回溯函数结束后,判断结果有无增加,如果增加了,说明该位置可切割;否则无法完成切割。
以s = "aaaaaaa",wordDict = ["aaaa", "aaa"]
为例,有一种回溯是"aaa", "aaa", "a"
,此时不是一个正确的切分,回溯把"a"
从路径删除,同时把memo[5]
置为False,表示以索引为5
结尾的子串无法得到一个正确的切割。
代码:
class Solution(object):
def wordBreak(self, s, wordDict):
"""
:type s: str
:type wordDict: List[str]
:rtype: List[str]
"""
wordDict = set(wordDict)
memo = [1] * len(s)
def backTrack(wordDict, pos, sub, res):
beforeNum = len(res)
if pos >= len(s):
res.append(" ".join(sub))
return
for i in range(pos, len(s)):
if s[pos:i+1] in wordDict and memo[i]:
sub.append(s[pos:i+1])
backTrack(wordDict, i+1, sub, res)
sub.pop()
if beforeNum == len(res):
memo[pos-1] = 0
res = []
backTrack(wordDict, 0, [], res)
return res