利用回溯法(深搜)搜索答案。
#include <iostream>
#include <vector>
using namespace std;
bool isline(string s, int start, int end)
{
while(s[start] == s[end]){
start++;
end--;
}
return start >= end;
}
void dfs(string s, vector<string> path, vector<vector<string> >& result, int depth)
{
if(depth == s.size()){
result.push_back(path);
return;
}
for(int i = depth; i < s.size(); ++i){
if(isline(s,depth,i)){
path.push_back(s.substr(depth, i-depth+1));
dfs(s,path,result,i+1); // Note: i+1 Not depth+1
path.pop_back();
}
}
}
int main()
{
string ss = "aaaaaaa";
vector<vector<string> > result;
vector<string> path;
dfs(ss,path, result,0);
for(auto s: result){
for(auto e:s){
cout << e<<" ";
}
cout << endl;
}
cout << result.size() << endl;
return 0;
}