【力扣】分割回文串(回溯法)
题目描述

一定要尽量按照模版写,不然的话稍微有点问题就很难改,把模版的思路搞清楚。
结束条件,backtrace函数的参数和同层循环体内的操作都是相辅相成的,一个写的不对也会影响到其他的地方。
如果按一种方案写实在改不正确,可以试着重新想一套新的三要素方案,不然可能怎么也改不好
贴一个第一遍写的错误代码:
class Solution {
public:
vector<vector<string> > res;
vector<string> path;
bool isHw(vector<string> vs){
string tmp;
//cout<<"在isHw函数内"<<endl;
for(int i = 0; i < vs.size(); i++){
tmp = vs[i];
//cout<<tmp<<" ";
reverse(vs[i].begin(), vs[i].end());
if(vs[i] != tmp){
//cout<<endl;
return false;
}
}
//cout<<endl;
return true;
}
void backtrace(const string& s, int startindex){
// if((isHw(path) && startindex != 0) || startindex == s.size()){
// if(isHw(path)){
// //cout<<"全是回文串"<<endl;
// res.push_back(path);
// }
// if(startindex != s.size())
// return ;
// }52
if(isHw(path)){
res.push_back(path);
}
if(startindex == s.size()){
return ;
}
//cout<<"startindex:"<<startindex<<endl;
for(int i = startindex+ 1; i < s.size(); i++){
path.pop_back();
path.push_back(s.substr(startindex, i - startindex));
path.push_back(s.substr(i, s.size() - i));
//cout<<s.substr(startindex, i)<<" "<<s.substr(i, s.size())<<endl;
backtrace(s, startindex+1);
path.pop_back();
path.pop_back();
path.push_back(s.substr(i, s.size() - i));
}
}
vector<vector<string>> partition(string s) {
path.push_back(s);
res.clear();
if(isHw(path)){
res.push_back(path);
}
backtrace(s, 0);
return res;
}
};
。。。问题有一大堆
这种总是维持path包含s的全部字符的方法太麻烦了。你可以看到不断压入弹出有多麻烦
下面的代码中是将path从空白开始慢慢填入的。
正确代码:
class Solution {
private:
vector<vector<string>> result;
vector<string> path; // 放已经回文的子串
void backtracking (const string& s, int startIndex) {
// 如果起始位置已经大于s的大小,说明已经找到了一组分割方案了
if (startIndex >= s.size()) {
result.push_back(path);
return;
}
for (int i = startIndex; i < s.size(); i++) {
if (isPalindrome(s, startIndex, i)) { // 是回文子串
// 获取[startIndex,i]在s中的子串
string str = s.substr(startIndex, i - startIndex + 1);
path.push_back(str);
} else { // 不是回文,跳过
continue;
//直接跳过,因为只有当当前子串是回文串的时候才能继续向下递归
}
backtracking(s, i + 1); // 寻找i+1为起始位置的子串
path.pop_back(); // 回溯过程,弹出本次已经添加的子串
}
}
bool isPalindrome(const string& s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
if (s[i] != s[j]) {
return false;
}
}
return true;
}
public:
vector<vector<string>> partition(string s) {
result.clear();
path.clear();
backtracking(s, 0);
return result;
}
};

浙公网安备 33010602011771号