思路:
DP+DFS。
DP去找到可以切分的点,DFS根据DP提供的信息拼接单词。
class Solution {
public:
void dfs(vector<string> &ans, string &s, unordered_set<string> &wordDict, string str, int idx, vector<bool> &dp) {
string substr;
for(int len = 1; idx + len <= s.length(); ++len) {
if(dp[idx + len] && wordDict.count(s.substr(idx, len)) == 1) {
substr = s.substr(idx, len);
if(idx + len < s.length()) {
dfs(ans, s, wordDict, str + substr + " ", idx + len, dp);
}else {
ans.push_back(str + substr);
return;
}
}
}
}
vector<string> wordBreak(string s, unordered_set<string>& wordDict) {
vector<string> ans;
if(wordDict.size() == 0) return ans;
vector<bool> dp(s.size() + 1, false);
dp[0] = true;
//判断是否可以切分
for(int i = 1; i <= s.size(); ++i) {
for(int j = i - 1; j >= 0; --j) {
if(dp[j]) {
string temp = s.substr(j, i - j);
if(wordDict.find(temp) != wordDict.end()) {
dp[i] = true;
break;
}
}
}
}
//如果可以切分,DFS去切分
if(dp[s.size()]) {
dfs(ans, s, wordDict, "", 0, dp);
}
return ans;
}
};