cpp
复制代码
class Solution {
public:
vector<string> res; // 当前路径,用于存储一个可能的回文分割结果
vector<vector<string>> result; // 存储所有可能的回文分割结果
// 判断子串 s[left:right] 是否是回文
bool isPalindrome(const string& s, int left, int right)
{
// 左右双指针向中间收缩比较
for (int i = left, j = right; i < j; i++, j--)
{
// 如果发现不相等的字符,则不是回文
if (s[i] != s[j])
{
return false;
}
}
// 如果所有字符都相等,则是回文
return true;
}
// 回溯函数,用于生成所有可能的回文分割
void backtracing(string s, int index)
{
// 如果遍历到字符串的末尾,说明找到了一种分割方式
if (index >= s.size())
{
result.push_back(res); // 将当前路径加入结果集
return;
}
// 从当前索引开始,遍历字符串
for (int i = index; i < s.size(); i++)
{
// 如果 s[index:i] 是回文
if (isPalindrome(s, index, i))
{
// 将当前回文子串加入路径
string str = s.substr(index, i - index + 1);
res.push_back(str);
// 递归处理子串 s[i+1:end]
backtracing(s, i + 1);
// 回溯,移除当前回文子串
res.pop_back();
}
else
{
// 如果不是回文,继续检查下一个子串
continue;
}
}
}
// 主函数,初始化回溯并返回结果
vector<vector<string>> partition(string s)
{
backtracing(s, 0); // 从索引 0 开始进行回溯
return result; // 返回所有可能的回文分割
}
};