回溯算法:分割回文串
在for (int i = startIndex; i < s.size(); i++)
循环中,我们 定义了起始位置startIndex,那么 [startIndex, i] 就是要截取的子串。
class Solution {
public:
vector<vector<string>> res;
vector<string> path;
vector<vector<string>> partition(string s) {
backtrack(s, 0);
return res;
}
bool isP(string s)
{
int begin = 0;
int end = s.size() - 1;
while(begin < end)
{
if(s[begin] != s[end])
return false;
++begin;
--end;
}
return true;
}
void backtrack(string s, int startIndex)
{
if(startIndex >= s.size())
{
res.push_back(path);
return;
}
for(int i = startIndex; i < s.size(); i++)
{
string tmp = s.substr(startIndex, i - startIndex + 1);
if(isP(tmp))
{
path.push_back(tmp);
}
else
{
continue;
}
backtrack(s, i + 1);
path.pop_back();
}
}
};