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"]
.
思路:下面的代码超时了
class Solution {
public:
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
int n = s.size();
vector< vector<bool> > record(n, vector<bool>(n, false));
vector<bool> f(n, false);
for (int i = 0; i < n; i++){
for (int j = i; j < n; j++){
if ((i == 0 || f[i-1]) && wordDict.count(s.substr(i, j - i + 1))){
f[j] = true;
record[i][j] = true;
}
}
}
vector<string> res;
if (!f[n - 1]) return res;
vector<string> path;
dfs(0, path, s, record,res);
return res;
}
void dfs(int level, vector<string> &path, string &s, vector< vector<bool> > &record, vector<string> &res){
if (level == s.size()){
string tmp;
for (auto iter = path.crbegin(); iter != path.crend(); ++iter)
tmp += *iter + " ";
tmp.erase(tmp.size() - 1, 1);
res.push_back(tmp);
return;
}
for (int i = level; i < s.size(); i++){
if (record[level][i]){
path .push_back(s.substr(level,i-level+1));
dfs(i + 1, path, s, record, res);
path.pop_back();
}
}
}
};
思路:下面的代码超时了