LeetCode 140. Word Break II
2016-04-24 08:57
471 查看
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
// I currently only do it using backtracking. But this has high complexity..... need to think about how to do it using DP.
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"].
// I currently only do it using backtracking. But this has high complexity..... need to think about how to do it using DP.
void wordBreak(string s, int pos, vector< vector<string > >& res, vector<string>& path, unordered_set<string>& wordDict) { if(pos == s.size()) { res.push_back(path); return; } for(int i = pos; i < s.size(); ++i) { string tmp = s.substr(pos, i - pos + 1); if(wordDict.find(tmp) != wordDict.end()) { path.push_back(tmp); wordBreak(s, i + 1, res, path, wordDict); path.pop_back(); } } } vector<string> wordBreak(string s, unordered_set<string>& wordDict) { vector< vector<string> > res; vector<string> path; wordBreak(s, 0, res, path, wordDict); vector<string> result; for(int i = 0; i < res.size(); ++i) { string tmp = ""; for(int j = 0; j < res[i].size(); ++j) { tmp = tmp + " " + res[i][j]; } result.push_back(tmp); } return result; } // test int main(void) { string test = "aaaaa"; unordered_set<string> wordDict{"a", "aaa", "aa", "aaaaa", "aaaa"}; vector<string> res = wordBreak(test, wordDict); for(auto iter : res) { cout << iter << endl; } }
相关文章推荐
- C++作业4
- 第一冲刺阶段——站立会议第七天4月24日
- Laravel的三种安装方法总结
- FZUOJ-2222-ABCDEFG From 校赛 A
- 班级派团队项目小计(七)
- 【BZOJ3489】A simple rmq problem
- dto与po转换类
- 转发:RocketMQ与kafka的对比
- 只要10000小时 你就是出类拔萃的人
- 【BZOJ4358】permu
- 番茄工作法总结(一边用一边自己修改,让它真正成为你的帮手)
- andorid Activity和Service音乐播放器
- Java多线程编程中线程锁与读写锁的使用示例
- JAVA-Java基础语法
- 【PA2011】Kangaroos
- Linux 链接
- HDU-5760 Machine (水 十进制化成三进制) From BestCoder #81(dir2)
- 通知的使用和通知对键盘的监听
- Android性能优化
- IPerf——网络测试工具介绍与源码解析(1)