#include <iostream>
#include<stdlib.h>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
string str = "catsanddog";
vector<string> wordlist= { "cat", "cats", "and", "sand", "dog" };
vector<vector<string>>ans;//所有答案
vector<string>path;
bool cmp(string left, string right) {
return left.length() < right.length() ? true : false;
}
void init() {
sort(wordlist.begin(), wordlist.end(), cmp);
//先按长度排序,减少后面遍历的情况;也可以
//用map存储前缀?以空间换时间-----
}
void print() {
if(ans.size()==0){
cout<<"no answer"<<endl;
return;
}
for (int i = 0; i < ans.size(); i++) {
for (int j = 0; j < ans[i].size(); j++)
cout << ans[i][j]<< " ";
cout << endl;
}
}
//rest表示匹配剩下的字符串
void process(string rest) {
if (rest == "") {
ans.push_back(path);
return;
}
for (int i = 0; i<wordlist.size() && wordlist[i].length() <= rest.length();i++) {
if (rest.substr(0, wordlist[i].length()) == wordlist[i]) {
path.push_back(wordlist[i]);
process(rest.substr(wordlist[i].length()));
path.pop_back();
}
}
}
int main() {
init();
process(str);
print();
system("pause");
return 0;
}