140. Word Break II (String; DP)
2015-10-29 06:47
351 查看
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"].
思路:需要知道从哪到哪是一个单词,所以状态选用二维数组。
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> wordBreak(string s, unordered_set<string>& wordDict) { results.clear(); if(s.size() < 1 || wordDict.empty()) return results; vector<vector<bool>> flag(s.length(),vector<bool>(s.length()+1, false)); //string, started from i with length j, can be found at least one form in the dict string str; for(int l = 1; l <= s.length();l++) //先把l小的处理完,有利于第三个for循环的判断 { for (int i = 0; i <= s.length()-l; i++) { str = s.substr(i,l); if(wordDict.find(str)!=wordDict.end()) //find one form in dict { flag[i][l] = true; continue; } for(int k = 1; k < l; k++){ //check string started from i with length l can be divided by the words in dict if(flag[i][k] && flag[i+k][l-k]){ flag[i][l] = true; break; } } } } if (!flag[0][s.length()]) { return results; } string pre = ""; dfs(s,pre, flag, wordDict, 0); return results; } void dfs(string &s, string pre, vector<vector<bool>> &dp, unordered_set<string> &dict, int start) { if(start == s.length()) { results.push_back(pre); return; } string backup = pre; string tmp; for(int i = 1; i <= s.length()-start;i++) { if(!dp[start][i]) continue; tmp = s.substr(start, i); if (dict.find(tmp)==dict.end()) continue; if(pre=="") pre += tmp; else pre = pre + " " + tmp; dfs(s, pre, dp, dict, start+i); pre = backup; //backtracking } } private: vector<string> results; };
相关文章推荐
- 恶意软件感染MySQL服务器 成为全球DDoS僵尸网络一部分
- sgit增加搜索功能
- 5.2 Binary to String
- Find Minimum in Rotated Sorted Array
- 面试总结2015-10-29
- Convert Sorted Array to Binary Search Tree - LeetCode
- 5.6 Conversion
- Kd-Tree算法原理和开源实现代码
- 5.1 Insertion
- LeetCode Expression Add Operators
- [LeetCode] Binary Tree Preorder Traversal
- iptables—icmp请求与响应规则:
- CryEngine3渲染引擎剖析
- 花10分钟看一下少走30年弯路
- 小、快、灵:康宁称雄光通信市场的秘诀
- HP Helion公有云宣布停服 放弃或是为了更好地进攻
- 桌面虚拟化,你还担心什么?
- 不疯魔,不成活,Rackspace为什么对管理云如此狂热
- 云计算每周之“红黑榜”
- 施耐德电气美国研发中心揭秘之旅