Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. You may assume the dictionary does not contain duplicate words.
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"]
.
UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.
上题,我用递归没解出来,这题上头了必须用递归写出来。
然而time limit exceeded,百思不得其解
在discuss中看见这样一段话
if you are getting TLE despite the correct DP or DFS solution, it might be because the largest test input is like this
["aa..(lots of 'a').b", "a","aaaaa"...so on]
As you can see this test case should return empty as last character in input string is b, which is not in the dictionary. So all the work in DP/DFS is a waste
To escape from TLE, just put a check first whether the input string s is breakable or not..if breakable then try to break it using your algo
一堆a中出了一个b!原来只要加一个判断是否可分割即可
附上自己的代码:
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
vector<string> res;
unordered_set<int> visited;
if(breakable(s,wordDict))
help(s,wordDict,res,"",0);
return res;
}
void help(string &s,vector<string> &wordDict,vector<string> &res,string temp,int index){
if(index==s.size()){
res.push_back(temp);
return;
}
for(int i=index;i<s.size();i++){
string t=s.substr(index,i-index+1);
if(find(wordDict.begin(),wordDict.end(),t)!=wordDict.end()){
t+=i==s.size()-1?"":" ";
help(s,wordDict,res,temp+t,i+1);
}
}
}
bool breakable(string &s,vector<string> &wordDict){
if(wordDict.size()==0) return false;
vector<bool> dp(s.size()+1);
dp[0]=true;
for(int i=1;i<=s.size();i++){
for(int j=i-1;j>=0;j--){
if(dp[j]){
string temp=s.substr(j,i-j);
if(find(wordDict.begin(),wordDict.end(),temp)!=wordDict.end()){
dp[i]=true;
break;
}
}
}
}
return dp[s.size()];
}
};