leetcode:word break II
2015-12-15 21:22
477 查看
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 =
dict =
A solution is
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: bool dfs(string s,int start, vector<string>& result, vector<string>& path, unordered_set<string>& wordDict ,unordered_set <int> & unmatch) { if(start==s.size()) { string tmp; for(auto word : path ) { tmp+=word; tmp+=" "; } result.push_back(tmp.substr(0,tmp.size()-1)); return true; } bool ret=false; for(int i=start; i<s.size(); i++) { string tmp = s.substr(start,i-start+1); //如果在i的位置分割过,不匹配,那就不要处理,直接跳过在后面的位置判断 if(wordDict.count(tmp)>0 && unmatch.count(i)==0 ) { path.push_back(tmp); bool subRet=dfs(s,i+1, result, path, wordDict, unmatch); path.pop_back(); if(subRet==false) unmatch.insert(i);//记录下i的位置,在这里分割过了,没有匹配的,以后就不要再在这里分割了 else ret=true;//为了告诉上一层,start 与start-1之间分开时可以匹配的 } } return ret; } vector<string> wordBreak(string s, unordered_set<string>& wordDict) { unordered_set<int> unmatch; vector<string> path; vector<string> ret; dfs(s, 0, ret, path, wordDict, unmatch); return ret; } };相关:word break I
相关文章推荐
- linux 目录/sys 解析
- Monkey
- 关于新浪微博sdk集成和MD5授权
- Qt-Q_INIT_RESOURCE
- Apple Notification Center Service--ANCS【转】
- HTML中心在页面上弹出自定义表单层(实现可能拖累)
- IOS网络开发(三)
- 指数循环节
- Arduino - 我偏爱的三块板子( Uno、Nano、Promini)针脚示意图
- 个人开发日志2015-12-15
- RFID扫描APP--source5
- php自己创建TPL模板引擎之初学习
- sys
- 电子商务网站专题页策划的6个必杀技
- ftp的20 21端口和主动被动模式
- Comparable与Comparator的区别
- ftp备份工具推荐,双向备份软件,文件同步软件,u盘备份软件推荐
- 由后缀数组构造字典序最小的原串
- Redis和Memcache的区别分析
- 58.UIView动画第二章(简单)