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"]
.
1.我的解答
参考word break1 dp
前面是判断dp[i] = (dp[j]==true && s(j...i) in dict)
现在是对于每个位置,用vector记录前面可以割的位置
然后用dfs找出这些word并连接起来
class Solution {
public:
void dfs(string s, vector<vector<int>>num, int begin, vector<string>& res, string str){
if(begin == s.size()){
res.push_back(str);
return;
}
for(int i = 0; i < num[begin].size(); i++){
int end = num[begin][i];
string temp = s.substr(begin, end-begin);
string strs = str;
strs += temp;
if(end < s.size()) strs += " ";
dfs(s, num, end, res, strs);
}
}
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
int n = s.size();
vector<vector<int>>num(n+1,vector<int>());
num[n].push_back(n);
for(int i = n-1; i >= 0; i--){
for(int j = i+1; j <= n; j++){
if(num[j].size() == 0) continue; //有位置存入,相当于true;没有位置存入,相当于false,直接跳过,体现DP
string str = s.substr(i, j-i);
if(wordDict.find(str) != wordDict.end()){
num[i].push_back(j);
}
}
}
vector<string>res;
string str;
dfs(s, num, 0, res,str);
return res;
}
};