暴力递归
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)
博客介绍了暴力递归和带备忘录的递归。暴力递归存在大量重复子问题计算,会导致时间超时。而带备忘录的递归可避免重复计算相同子问题,是对暴力递归的优化。
724

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



