|
|
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
一种写的比较多,动态规划改记忆化递归写法:
- class Solution(object):
- def wordBreak(self, s, wordDict):
- """
- :type s: str
- :type wordDict: List[str]
- :rtype: bool
- """
- ref={}
-
- def dfs(i):
- if i==0: ref[0]=True
- if i in ref: return ref[i]
- ref[i]=False
- for j in range(i):
- if s[j:i] in wordDict and dfs(j):
- ref[i]=True
- return ref[i]
-
- return dfs(len(s))
复制代码
另一种记忆化递归:
- class Solution:
- def __init__(self):
- self.cache=collections.defaultdict()
- self.cache[""]=True
-
- def wordBreak(self, s: str, wordDict: List[str]) -> bool:
- if s in self.cache: return self.cache[s]
-
- for i in range(len(s)):
- if s[:i+1] in wordDict:
- if self.wordBreak(s[i+1:], wordDict):
- self.cache[s]=True
- return True
- self.cache[s]=False
- return False
-
复制代码
求分析两种写法的优缺点。复杂度感觉应该是一样的n^2。个人比较容易理解第二种写法。
谢谢。
|
上一篇: 面试不用动态规划用记忆化递归可不可以?下一篇: 对于mock interview的疑问
|