[LeetCode] Word Break II
来源:互联网 发布:淘宝p图软件 2016 编辑:程序博客网 时间:2024/06/03 11:43
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"]
.
class Solution {public: vector<string> ans; vector<string> wordBreak(string s, unordered_set<string> &dict) { int n = s.size(); vector<bool> p(n + 1,false); p[0] = true; for(int i = 0;i < n;i ++){ if(p[i]){ for(int step = 1;i + step - 1 < n;step ++){ if(dict.count(s.substr(i,step)) > 0) p[i + step] = true; } } } if(p[n]) dfs("",s,dict,0,p); return ans; } void dfs(string ansS,string s, unordered_set<string> &dict,int start,vector<bool> p) { for(int len = 1; start + len - 1 < s.size();len ++){ if(p[start + len] && dict.count(s.substr(start,len)) > 0){ string x = s.substr(start,len); if(start + len < s.size()) dfs(ansS + x + " ",s,dict,start + len,p); else ans.push_back(ansS + x); } } }};
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
- jsoncpp 构造空数组
- Android 出现case expressions must be constant expressions
- C# 数据结构基础-实现循环队列
- python中os和os.path模块
- (30 hackdays day 8) Physical web - 给鞋子一个网址
- [LeetCode] Word Break II
- (30 hackdays day 9) Rekognition - 借我借我一双慧眼吧
- python解析xml并按照其结构输出
- Linux Nginx
- 取一个字符串的子串
- iOS 开发 - iOS Core Animation学习记录
- 2015年的科技界将发生这十件大事
- 10款最好的 Bootstrap 3.0 免费主题和模板
- Android学习笔记八.LauncherActvity 之LauncherActivity、PreferenceActivity、PreferenceFragment