暴力递归
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
def helper(tmps):
if not tmps: # tmps为空字符串是返回真
return True
for i in range(1, len(tmps)+1):
if tmps[:i] in wordDict: # 当tmps[:i]在wordDict中时,就转换为子问题:判断tmps[i:]是否可由wordDict中的词组成
if helper(tmps[i:]):
return True
return False
return helper(s)
该版本时间超时,是因为大量重复子问题计算。
可通过添加备忘录避免重复计算相同子问题
带备忘录的递归
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> bool:
dic = {}
def helper(tmps):
if not tmps:
return True
# 将tmps是否可由wordDict中词构成的结果存到dic中,
if tmps in dic: # 当判断tmps存在于dic时,说明该问题已经计算过可直接返回结果。
return dic[tmps]
else:
for i in range(1, len(tmps)+1):
if tmps[:i] in wordDict:
if helper(tmps[i:]):
dic[tmps] = True
return True
dic[tmps] = False
return False
return helper(s)