leetcode -- Word Break I & II -- 重点
2015-12-18 09:53
405 查看
Word Break
https://leetcode.com/problems/word-break/本以为是一道dfs的递归题目,但是超时。对于下面的case,会超时
“aaaaaaaa”
[“aaaa”,”aa”,”a”]
递归程序
def wordBreak(self, s, wordDict): """ :type s: str :type wordDict: Set[str] :rtype: bool """ if not s: return True for i in xrange(len(s) + 1): if s[:i] in wordDict: if i == len(s): return True #print i j = i + 1 while (s[:j] in wordDict): j += 1 #print j return self.wordBreak(s[j - 1:], wordDict) return False
实际上要用dp。最后求bool型变量的也可以用dp,
参考/article/4981569.html
class Solution: # @param s, a string # @param dict, a set of string # @return a boolean # @good coding! def wordBreak(self, s, dict): dp = [False for i in range(len(s)+1)] dp[0] = True#这里要注意给dp[0]初始化为True,比如s就一个word,刚好就在dict中。 for i in range(1, len(s)+1): for k in range(i): if dp[k] and s[k:i] in dict: dp[i] = True return dp[len(s)]
Word Break II
https://leetcode.com/problems/word-break-ii/思路就是上一题的dp结合dfs
参考:
/article/4981570.html
class Solution: # @param s, a string # @param dict, a set of string # @return a list of strings def check(self, s, dict): dp = [False for i in range(len(s)+1)] dp[0] = True for i in range(1, len(s)+1): for k in range(0, i): if dp[k] and s[k:i] in dict: dp[i] = True return dp[len(s)] def dfs(self, s, dict, stringlist): if self.check(s, dict): if len(s) == 0: Solution.res.append(stringlist[1:]) for i in range(1, len(s)+1): if s[:i] in dict:#这里的子节点就是递增的prefix string self.dfs(s[i:], dict, stringlist+' '+s[:i]) def wordBreak(self, s, dict): Solution.res = [] self.dfs(s, dict, '') return Solution.res
相关文章推荐
- HDOJ2094 拓扑排序 STL中set和map的应用 产生冠军
- 增删改查
- oracle 赋予、回收账户权限
- 工作一年多了,跳槽,总结下最近面试面试官经常提到的问题,希望能帮到大家
- 帧率、码流与分辨率相关知识
- HDOJ2019 数列有序
- 自定义图片形状
- Django 设置template的全局变量
- 解决乱码
- [转]最新版SDWebImage的使用
- 不可摸数
- 关系型数据库 (数据库类型)
- Cookie简单是现自动登陆功能
- Alamofire json Alamofire2.0使用
- 双网卡双IP同时连通
- [IOS 开发] 获取当前设备可用内存及所占内存
- java中的三个引用类 SoftReference, WeakReference 和 PhantomReference的区别
- ubuntu开机自动项详解
- VC小技巧收集————如何修改窗口标题
- Web系统开发构架再思考-前后端的完全分离