如何解决断字Leetcode#139Python解决方案超时-备忘录不起作用吗?
我正在解决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]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。