140. Word Break II[hard]
来源:互联网 发布:中国电信网络承载策略 编辑:程序博客网 时间:2024/06/03 11:30
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"]
.
先对单词表建trie树,然后dfs就好
但直接dfs会导致超时。
优化方式是:建一个map,存下搜索过的string s的所有答案,虽然空间消耗大,但是减少了dfs次数
struct node{ vector<node*> a; bool word; node() { word = false; a.resize(26,NULL); }};class Solution {public: node* root; set<string> SET; vector<string> ans; map<string, vector<string>> mp; void insert(string word) { node* now = root; for(int i=0;i<word.size();i++) if(now->a[ word[i]-'a' ]!=NULL) now = now->a[ word[i]-'a' ]; else { now->a[ word[i]-'a' ] = new node(); now = now->a[ word[i]-'a' ]; } now->word = true; } vector<string> getans(string s, node* r) { if(mp.find(s)!=mp.end())return mp[s]; vector<string> res; if(!s.length()) { res.push_back(""); mp[s] = res; return mp[s]; } node* now = r; int l = s.length(); for(int i = 0 ; i < l ; ++i ) { if(now->a[ s[i]-'a' ]) now = now->a[ s[i]-'a' ]; else { mp[s] = res; return mp[s]; } if(now->word) { vector<string> nxt = getans(s.substr(i+1),r); for(auto iter: nxt) { string tmp = s.substr(0,i+1) + (iter.length()?" ":"") + iter; res.push_back(tmp); } } } mp[s] = res; return mp[s]; } vector<string> wordBreak(string s, unordered_set<string>& wordDict){root = new node(); for(auto iter = wordDict.begin();iter!=wordDict.end();iter++) insert(*iter); vector<string> ans = getans(s,root); return ans; } };
0 0
- 140. Word Break II[hard]
- Hard-题目45:140. Word Break II
- 140.Word Break II
- 140. Word Break II
- 140. Word Break II
- 140. Word Break II
- 140. Word Break II
- 140. Word Break II
- 140. Word Break II
- 140. Word Break II
- 140. Word Break II
- 140. Word Break II
- 140. Word Break II
- 140. Word Break II
- 140. Word Break II
- 140. Word Break II
- [leetcode] 140.Word Break II
- LeetCode 140. Word Break II
- HDOJ--1181|变形课
- 1613-3-傅溥衍 总结《2016年11月30日》【连续第六十一天总结】
- Intellij IDEA使用 JRebel 搭配 maven-jetty-plugin插件实现热部署
- 我如何在计算机视觉顶级会议CVPR上发表论文?
- 博为峰Java技术题 ——JavaSE Java方法Ⅳ
- 140. Word Break II[hard]
- 创建自定义类的对象数组
- 递归求二项式系数值
- mybatis generator
- 分布式锁
- 数据库表的行和列倒置
- LinkedBlockingQueue示例
- POJ 1275 Cashier Employment(差分约束)
- c++ 数据结构 用递归方法解决迷宫问题