#include <bits/stdc++.h>
using namespace std;
unordered_map<int, vector<string>> memo;
vector<string> backtracking(string &s, int start, unordered_set<string> set) { if (start == s.size()) return {""};
if (memo.count(start)) return memo[start];
cout << " start = " << start << endl;
vector<string> ret;
for (int len = 1; len + start <= s.size(); len++) { string str = s.substr(start, len); if (set.count(str)) { vector<string> next = backtracking(s, start + len, set); for (auto &ss : next) { cout << " ss = " << ss << endl; if (ss == "") ret.push_back(str); else ret.push_back(str + " " + ss); } } } memo[start] = ret; cout << " start " << start << " memo[start] " << endl; for (int i = 0; i < memo[start].size(); i++) { cout << memo[start][i] << endl; } return ret; }
int main() {
string s = "catsanddog"; vector<string> wordDict = {"cat", "cats", "and", "sand", "dog"}; unordered_set<string> set(wordDict.begin(), wordDict.end()); vector<string> ans = backtracking(s, 0, set);
cout << endl; cout << endl; for (int i = 0; i < ans.size(); i++) { cout << ans[i] << endl; } system("pause"); return 0; }
|