回溯
每次递归查看tmp是否为回文字符串数组;
class Solution {
public:
vector<vector<string>> partition(string s) {
backtrack(s);
return res;
}
private:
vector<vector<string>> res;
vector<string> tmp;
void backtrack(string s){
if(!ispal(tmp)) return;
if(!s.size()) {
res.push_back(tmp);
return;
}
for(int i=1;i<=s.size();i++)
{
tmp.push_back(s.substr(0,i));
backtrack(s.substr(i));
tmp.pop_back();
}
return ;
}
bool ispal(vector<string> tmp){
for(auto t:tmp){
int start=0;
int end=t.size()-1;
while(start<end){
if(t[start]==t[end])
{
start++;
end--;
}
else return false;
}
}
return true;
}
};
优化:在加入tmp的时候判断是否为回文字符串
class Solution {
public:
vector<vector<string>> partition(string s) {
backtrack(s);
return res;
}
private:
vector<vector<string>> res;
vector<string> tmp;
void backtrack(string s){
if(!s.size()) {
res.push_back(tmp);
return;
}
for(int i=1;i<=s.size();i++)
{
if(ispal(s.substr(0,i))){
tmp.push_back(s.substr(0,i));
backtrack(s.substr(i));
tmp.pop_back();
}
}
return ;
}
bool ispal(string t){
if(!t.size()) return true;
int start=0;
int end=t.size()-1;
while(start<end){
if(t[start]==t[end])
{
start++;
end--;
}
else return false;
}
return true;
}
};