LeetCode刷题笔录Word Break II
来源:互联网 发布:mac怎么切换独立显卡 编辑:程序博客网 时间:2024/05/17 10:55
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
s = "catsanddog"
,
dict = ["cat", "cats", "and", "sand", "dog"]
.
A solution is ["cats and dog", "cat sand dog"]
.
public class Solution { public List<String> wordBreak(String s, Set<String> dict) { List<String> res = new ArrayList<String>(); if(s.length() == 0 || s == null) return res; recursive(s, 0, dict, "", res); return res; } public void recursive(String s, int index, Set<String> dict, String string, List<String> res){ if(index >= s.length()){ res.add(string); return; } StringBuilder builder = new StringBuilder(); for(int i = index; i < s.length(); i++){ builder.append(s.charAt(i)); if(dict.contains(builder.toString())){ String str = string.isEmpty() ? builder.toString() : (string + " " + builder.toString()); recursive(s, i + 1, dict, str, res); } } }}
大数据集是通不过的。网上看到了一个剪枝的办法,就是利用DP的思想,如果某个点i在之前的搜索中没有得到结果,那么以后就不进行搜索了。
public class Solution { public List<String> wordBreak(String s, Set<String> dict) { List<String> res = new ArrayList<String>(); if(s.length() == 0 || s == null) return res; boolean[] possible = new boolean[s.length() + 1]; Arrays.fill(possible, true); recursive(s, 0, dict, "", res, possible); return res; } public void recursive(String s, int index, Set<String> dict, String string, List<String> res, boolean[] possible){ if(index >= s.length()){ res.add(string); return; } StringBuilder builder = new StringBuilder(); for(int i = index; i < s.length(); i++){ builder.append(s.charAt(i)); //only perform search if there are possible solutions in level i + 1 if(dict.contains(builder.toString()) && possible[i + 1]){ String str = string.isEmpty() ? builder.toString() : (string + " " + builder.toString()); int beforeSearch = res.size(); recursive(s, i + 1, dict, str, res, possible); //if the result size is not changed after the search, then there is no solution at i if(beforeSearch == res.size()) possible[i + 1] = false; } } }}
0 0
- LeetCode刷题笔录Word Break II
- LeetCode刷题笔录Word Break II
- LeetCode刷题笔录Word Break
- [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
- Android分享中,如何过滤指定的应用,并且对不同的分享方式发送不同的内容?
- Cocos2d-X开发中国象棋《一》功能介绍
- java网络爬虫:
- Orcad中较好的习惯背景
- cocos2d学习之CCColor
- LeetCode刷题笔录Word Break II
- 散列函数(哈希函数)算法
- 如何修改eclipse 格式化行长度
- Spring如何使用aop切入controller层---问题笔记
- Window8 FTP站点构建
- 关于Certificate、Provisioning Profile、App ID的介绍及其之间的关系
- 第11周项目1.2用函数输出星号图
- C++中#ifdef、#endif等宏的使用
- WPF学习(第九章)命令