[LeetCode] Word Break II
来源:互联网 发布:js控制div左右移动 编辑:程序博客网 时间:2024/06/18 08:33
leetcode 原题
这个题可以用dfs做,思路简单,但是也可以用dp做。
Dp的做法基于Word Break I
也很费空间,每次的结果都要存起来,以免后面要用。
存到最后一个结果的时候,那就是题目要返回的值,也就是多少种词的情况。
至于最后那个原封不动的word break I的代码,是为了一个超大的全是aaaaaaaaaa...aaaa的集合量身打造的。因为如果不能break,我们就不费事搞了,直接返回。
public List<String> wordBreak(String s, Set<String> dict) { int n=s.length(); boolean[] dp=new boolean[n+1]; dp[0]=true; List<List<String>> words = new ArrayList<List<String>>(); for (int i = 0; i <= n; i++) words.add(new ArrayList<String>()); words.get(0).add(""); if(!wordBreakI(s,dict)) return new ArrayList<String>(); for(int i=1;i<=n;i++){ for(int j=0;j<i;j++){ String temp=s.substring(j,i); if(dp[j] && dict.contains(temp)){ dp[i]=true; for (String str : words.get(j)) { if (str.equals("")) words.get(i).add(String.format("%s", temp)); else words.get(i).add(String.format("%s %s", str, temp)); } } } } return words.get(n); } public boolean wordBreakI(String s, Set<String> dict) { //dp int n= s.length(); boolean[] dp=new boolean[n+1]; dp[0]=true; for(int i=1;i<=n;i++){ for(int j=0;j<=i;j++){ if(dp[j] && dict.contains(s.substring(j,i))){ dp[i]=true; } } } return dp[n]; }
0 0
- [leetcode]Word Break II
- LeetCode:Word Break II
- Leetcode: Word Break II
- [LeetCode] Word Break II
- [LeetCode]Word Break II
- LeetCode | Word Break II
- [LeetCode] - Word Break II
- LeetCode - Word Break II
- Leetcode Word Break II
- [LeetCode] Word Break II
- Word Break II -- LeetCode
- LeetCode (Word Break II )
- Leetcode--Word Break II
- Leetcode: Word Break II
- LeetCode Word Break II
- Word Break II leetcode
- [leetcode]Word Break II
- leetcode -- word break II
- 常指针与指向常对象的指针
- RQNOJ PID729 / 相同的后K位
- 数据库表批量操作
- Overload和Override的区别
- php定义成NULL好还是定义成空字符串好
- [LeetCode] Word Break II
- git代理设置
- 电解电容和钽电容的区别是什么
- 回调函数的使用
- WEEK1-4: from L1(intro) to L7(debegging)
- Errors occurred during the build. Errors running builder 'DeploymentBuilder' on project 'myf'. java.
- 共用体
- jar调用本地xml文件方法
- unity连接MySQL数据库