问题描述
我正在解决leetcode #139,由于某种原因,我超出了时间限制。我使用备忘录的方式不正确吗?
class Solution:
memo = set()
def wordBreak(self,s: str,wordDict: List[str]) -> bool:
self.memo = set(wordDict)
return self.word_break(s)
def word_break(self,s):
if s in self.memo:
return True
for i in range(1,len(s)):
head = s[:i]
tail = s[i:]
head_possible = self.word_break(head)
tail_possible = self.word_break(tail)
if head_possible:
self.memo.add(head)
if tail_possible:
self.memo.add(tail)
if head_possible and tail_possible:
return True
return False
谢谢!
解决方法
- 如果我们仅启用lru_cache(),则您的解决方案无需TLE即可正常工作:
class Solution:
memo = set()
def wordBreak(self,s: str,wordDict: List[str]) -> bool:
self.memo = set(wordDict)
return self.word_break(s)
@lru_cache(None)
def word_break(self,s):
if s in self.memo:
return True
for i in range(1,len(s)):
head = s[:i]
tail = s[i:]
head_possible = self.word_break(head)
tail_possible = self.word_break(tail)
if head_possible:
self.memo.add(head)
if tail_possible:
self.memo.add(tail)
if head_possible and tail_possible:
return True
return False
- 这也会在没有超过时间限制的情况下通过:
class Solution:
def wordBreak(self,s,words):
dp = [False] * len(s)
for i in range(len(s)):
for word in words:
k = i - len(word)
if word == s[k + 1:i + 1] and (dp[k] or k == -1):
dp[i] = True
return dp[-1]