题目描述:
给了一个字典,问给定的字符串s能有多少种被字典构造出来的方式,返回每一种构造方式。
思路:
递归。用字典保存当前已有的构造方式。
代码:
class Solution {
public:
vector<string> wordBreak(string s, vector<string>& wordDict) {
map<string, vector<string> >m;
return dfs(s, wordDict, m);
}
vector<string> dfs(string s, vector<string>& wordDict, map<string, vector<string> >& m) {
if (m.count(s)) return m[s];
if (s == "") return {""};
vector<string> res;
for (string word : wordDict) {
if (s.substr(0, word.size()) != word) continue;
vector<string> remain = dfs(s.substr(word.size()), wordDict, m);
for (string r : remain) {
res.push_back(word + (r.empty() ? "" : " ") + r);
}
}
return m[s] = res;
}
};
好优雅…
第二次写。依然先超时,然后觉得这个map很优雅。