195.回溯算法:分割回文串(力扣)

代码解决

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; // 返回所有可能的回文分割
    }
};
  • 初始化输入字符串 s = "aab"。
  • 调用 partition 函数,该函数开始回溯。
  • 在 backtracing 函数中,从索引 0 开始遍历:
    • 第一次循环:
      • i = 0: 检查子串 s[0:0]("a"),是回文,将其加入当前路径 res = ["a"]。
      • 递归调用 backtracing,索引增加到 1。
    • 第二次循环:
      • i = 1: 检查子串 s[1:1]("a"),是回文,将其加入当前路径 res = ["a", "a"]。
      • 递归调用 backtracing,索引增加到 2。
    • 第三次循环:
      • i = 2: 检查子串 s[2:2]("b"),是回文,将其加入当前路径 res = ["a", "a", "b"]。
      • 递归调用 backtracing,索引增加到 3,等于字符串长度,当前路径 res 被加入结果集。
  • 回溯到上一个递归层次,移除当前路径的最后一个元素,继续循环检查其他子串。
  • 通过循环和递归的方式,最终找到所有可能的回文分割,并将其加入结果集。
相关推荐
老师我太想进步了20261 小时前
【数据结构-4】算法美学之顺序表
数据结构·算法
风影同志783241 小时前
编码器是激活函数吗?—— 一个看起来很像、其实不是的类比
算法
UIU1141 小时前
P1481 魔族密码
c++·算法·动态规划
文丑颜不良啊2 小时前
LeetCode1961~1980题目解析
java·leetcode
文丑颜不良啊3 小时前
LeetCode2001~2020题目解析
java·leetcode
加宝的起点雷达5 小时前
40 条候选里 38 条来自同一个源,主卡整屏重样
人工智能·算法·创业
秋天的怀念_David5 小时前
算法一千零一夜 · 第二十六夜 协议的母语
java·spring boot·算法
文丑颜不良啊6 小时前
LeetCode2021~2040题目解析
java·leetcode