链接:140. 单词拆分 II
题解:https://leetcode-cn.com/problems/word-break-ii/solution/dan-ci-chai-fen-ii-by-leetcode-solution/
class Solution {
private:
// 表示以key为下标开始,value表示可以到达字符串末尾的清空
unordered_map<int, vector<string>> ans;
unordered_set<string> wordSet;
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
wordSet = unordered_set(wordDict.begin(), wordDict.end());
backtrack(s, 0);
return ans[0];
}
void backtrack(const string& s, int index) {
if (!ans.count(index)) {
// 如果打到达末尾直接返回,并且给ans[index]一个空
if (index == s.size()) {
ans[index] = {""};
return;
}
ans[index] = {};
for (int i = index + 1; i <= s.size(); ++i) {
//substr表示以index为开头,长度为i-index
string word = s.substr(index, i - index);
// 如果字典有这个
if (wordSet.count(word)) {
// 回溯下一个字符,以i为开始
backtrack(s, i);
// 通过以i为开头的字符串,获得以index为开头字符串的情况
// 如果succ为空表示当前word为最后一个字符串
for (const string& succ: ans[i]) {
ans[index].push_back(succ.empty() ? word : word + " " + succ);
}
}
}
}
}
};