题目大意:
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"]
.
意思就是:
给定字符串s和字典集合dict, 求s分成dict中字符的几种情况.
我最开始的代码如下(直接用递归,导致超时):
class Solution{ public: vector<string> wordBreak(string s, unordered_set<string> &dict){ vector<string> result; string temp; int len = s.size()-1; recursion(s, dict, 0, 0,len, temp, result); return result; } void recursion(string s, unordered_set<string>& dict, int start, int end, int len, string temp, vector<string>& result){ if(end == len+1){ result.push_back(temp); return; } for(int i=end;i<=len;i++){ string hehe = s.substr(start, i-start+1); if(dict.count(hehe) == 0){ continue; } else{ temp += hehe + " "; recursion(s, dict, i+1, i+1, len, temp, result); temp = ""; } } } };
代码如下:
class Solution { public: vector<string> wordBreak(string s, unordered_set<string> &dict) { int len = s.size(); vector<string> result; vector< vector<bool> > storage(len, vector<bool>(len, false)); for(int i=0;i<len;i++){ for(int j=i;j<len;j++){ if(dict.count(s.substr(i, j-i+1))){ storage[i][j] = true; } } } bool label = false; for(int i=0;i<len;i++){ if(storage[i][len-1] == true){ label = true; break; } } if(!label){ return result; } vector<int> slot; dfsTravel(s, 0, slot, result, storage); return result; } void dfsTravel(string s, int start, vector<int> slot, vector<string>& result, vector< vector<bool> > storage){ if(start == s.size()){ string str = s; for(int i=0;i<slot.size()-1;i++){ str.insert(slot[i]+i, " "); } result.push_back(str); return; } for(int i = 0;i<storage[start].size();i++){ if(storage[start][i] == true){ slot.push_back(i+1); dfsTravel(s, i+1, slot, result, storage); slot.pop_back(); } } } };