leetcode: Word Break 纪念又一次死在动态规划上
来源:互联网 发布:公交线路数据 编辑:程序博客网 时间:2024/05/06 13:51
动态规划是算法中的一个基本的算法,但是个人感觉变化很多,有时候知道能够用,但是却想不到思路。
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode"
,
dict = ["leet", "code"]
.
Return true because "leetcode"
can be segmented as "leet code"
.
public class Solution { public boolean wordBreak(String s, Set<String> wordDict) { int n = s.length(); boolean [][] me = new boolean[n+1][n+1]; return dfs(s,0,wordDict,me); } public boolean dfs(String s, int l, Set<String> wordDict, boolean [][] me){if(s == null || s.length() == 0 || l >= s.length()){ return true; }int n = s.length(); for(int i = l+1;i <= n;i++){ if(me[l][i]){ return dfs(s,i,wordDict,me); } if(wordDict.contains(s.substring(l,i))){ me[l][i] = true; if(dfs(s,i,wordDict,me)){ return true; } } }return false;} }
用动态规划,后来看了别人的思路之后,发现果然是非常典型的动态规划算法,分析如下:摘自水中的鱼的博客
一个DP问题。定义possible[i] 为S字符串上[0,i]的子串是否可以被segmented by dictionary.
那么
possible[i] = true if S[0,i]在dictionary里面
= true if possible[k] == true 并且 S[k+1,i]在dictionary里面, 0<k<i
= false if no such k exist.
自己根据思路写了一下,Accepted的代码如下:
public class Solution { public boolean wordBreak(String s, Set<String> wordDict) { int n = s.length(); boolean [] a = new boolean[n]; for(int i = 0;i < n;i++){ if(wordDict.contains(s.substring(0,i+1))){ a[i] = true; continue; } for(int j = 0;j < i;j++){ if(a[j] && wordDict.contains(s.substring(j+1,i+1))){ a[i] = true; } } } return a[n-1]; } }
耗时还是12ms,感觉这样的二重循环肯定要快很多,可是结果并没有,所有感到迷茫了。。。
0 0
- leetcode: Word Break 纪念又一次死在动态规划上
- [LeetCode] [动态规划] Word Break
- 【LeetCode】Word Break 动态规划
- 【LeetCode】Word Break II 动态规划
- LeetCode练习-动态规划算法-word-break
- '动态规划:word-break'
- 动态规划:word-break
- 动态规划——Word Break 拆分词句【LeetCode】
- 139. Word Break 动态规划
- Word Break II[动态规划&DFS]
- 动态规划问题系列---word break问题
- 牛客网第10题:动态规划 Word Break
- 13.12—动态规划—Word Break
- 动态规划、递归:word-break II
- leetcode 140. Word Break II 动态规划DP + DFS深度优先搜索
- 动态规划——word-break&&word-breakii
- 343.[LeetCode] 动态规划 Integer Break
- 343. Integer Break(LeetCode, C++, 动态规划)
- 黑马程序员---OC学习笔记之block的使用场景
- Android开发资源获取国内代理(转载)
- SQL中char、varchar、nvarchar的区别
- iOS学习网址收集
- 多对一双向关联关系理解与实践
- leetcode: Word Break 纪念又一次死在动态规划上
- android-发短信
- Memcached安装
- Redis学习笔记
- Managing Your App's Memory
- 深度学习(九)caffe预测、特征可视化python接口调用
- Android_Handler_入门
- android studio快捷键大全
- Updating to SVN 1.8 for Mac OS X 10.10 Yosemite (svn client is too old to work with working copy)