139. 单词拆分https://leetcode.cn/problems/word-break/description/?envType=study-plan-v2&envId=top-100-liked还是记忆化递归。dp也能做。
class Solution {
public:
bool wordBreak(string s, vector<string>& wordDict) {
unordered_set<string> uset;
for (string str : wordDict) {
uset.insert(str);
}
vector<int> mem(s.size(), -1);
function<bool(int)> dfs = [&](int start) -> bool {
if (start == s.size()) return true;
if (mem[start] != -1) return mem[start];
for (int i=start; i < s.size(); ++i) {
string sub = s.substr(start, i-start + 1);
if (uset.find(sub) != uset.end() && dfs(i + 1)) {
mem[start] = 1;
return true;
}
}
mem[start] = 0;
return false;
};
return dfs(0);
}
};