LeetCode 140 Word Break II 记忆化搜索 [Hard]
Given a string s
and a dictionary of strings wordDict
, add spaces in s
to construct a sentence where each word is a valid dictionary word. Return all such possible sentences in any order.
Note that the same word in the dictionary may be reused multiple times in the segmentation.
Solution
这里我们需要输出所有的方案。我们考虑记忆化搜索。具体来说,我们用一个 \(map\) 来维护字符串 \(s\) 对应的方案 \(map[s]\).
在搜索的过程中,我们按照分割的位置将字符串在 \(i\) 地方切割,如果后半段在 wordDict
里面,那我们按照同样的思路对前面进行切割
点击查看代码
class Solution {
private:
unordered_map<string, vector<string>> mp;
vector<string> comb(string w, vector<string> v){
for(int i=0;i<v.size();i++){
v[i] = v[i]+" "+w;
}
return v;
}
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
// memorize
if(mp.count(s)) return mp[s];
vector<string> ans;
if(find(wordDict.begin(),wordDict.end(),s)!=wordDict.end())ans.push_back(s);
for(int i=1;i<s.length();i++){
string w = s.substr(i);
if(find(wordDict.begin(), wordDict.end(),w)!=wordDict.end()){
// w exists
string resd = s.substr(0,i);
vector<string> v = comb(w, wordBreak(resd,wordDict));
ans.insert(ans.end(),v.begin(), v.end());
}
}
mp[s] = ans;
return ans;
}
};