官方题解https://leetcode-cn.com/problems/word-break-ii/solution/dan-ci-chai-fen-ii-by-leetcode-solution/
抄答案:
class Solution {
public:
unordered_set<string> wordDictSet;
unordered_map<int, vector<string>> sen; //记录每个下标对应的字符 以它开头形成的句子的集合
vector<string> wordBreak(string s, vector<string>& wordDict) {
wordDictSet=unordered_set(wordDict.begin(),wordDict.end());
backtrack(s,0);
return sen[0];
}
void backtrack(string &s, int idx){
if(!sen.count(idx)){ //如果这个下标对应的字符 没有以它开头形成的句子
if(idx==s.size()){
sen[idx]={""}; //如果idx指向s末尾,则idx对应的句子集合为一个空字符串(以s[idx]开头的句子为空字符串)
return;
}
sen[idx]={}; //对于非末尾的下标,往后看,看以s[idx]开头能形成哪些句子
for(int i=idx+1; i<=s.size(); ++i){
string word=s.substr(idx, i-idx); //取idx~i子串word
if(wordDictSet.count(word)){
backtrack(s,i); //如果子串word形成了单词,就在此基础上递归
for(string& t:sen[i]){ //修改以s[i]开头的句子集合
if(t.empty()) sen[idx].push_back(word); //如果句子为空,把“word”加入句子集合
else sen[idx].push_back(word+" "+t); //如果句子不为空,把“t word”加入句子集合
}
}
}
}
}
};