#include <iostream>
#include<stdlib.h>
#include<string>
#include<vector>
#include<set>
#include<math.h>
#include<map>
#include<unordered_map>
#include<algorithm>
#include<functional>
#include<queue>
using namespace std;
map<string, int>mymap;//key为元素,value为该元素出现的次数
vector<int>v;//记录字典中每个字符串的长度,并保留唯一,set排序
vector<string>ans;
void print() {
for (int i = 0; i < ans.size(); i++) {
cout << ans[i] << " ";
}
cout << endl;
}
void wordBreak(string s, vector<string> wordDict) {
if (s.empty()) {
print();
return;
}
if (s.length() < v[0])
return;
for (int i = 0; i < v.size(); i++) {
string tmp="";
if(s.length()>=v[i])
tmp = s.substr(0, v[i]);
if (mymap.find(tmp) != mymap.end()){
ans.push_back(tmp);
wordBreak(s.substr(v[i]),wordDict);
//复原
ans.pop_back();
}
}
}
void getLength(vector<string>wordDict) {
set<int>length_of_words;
for (int i = 0; i < wordDict.size(); i++) {
length_of_words.insert(wordDict[i].length());
mymap.insert(pair<string,int>(wordDict[i], 1));
}
for (set<int>::iterator it = length_of_words.begin(); it != length_of_words.end(); it++) {
v.push_back(*it);
}
}
int main() {
vector<string>wordDict = { "apple", "pen", "applepen", "pine", "pineapple" };
string str = "pineapplepenapple";
getLength(wordDict);
wordBreak(str, wordDict);
system("pause");
return 0;
}