【LeetCode热题100】【回溯】分割回文串

题目链接:131. 分割回文串 - 力扣(LeetCode)

要找出所有分割这个字符串的方案使得每个子串都是回文串,写一个判断回文串的函数,深度遍历回溯去找出所有分割方案,判断分割的子串是否是回文串

复制代码
class Solution {
public:
    vector<vector<string> > ans;
    vector<string> an;
    string s;

    bool isPalindromes(int left, int right) {
        while (left < right) {
            if (s[left++] != s[right--])
                return false;
        }
        return true;
    }

    void dfs(int i) {
        if (i == s.size()) {
            ans.push_back(an);
            return;
        }
        for (int j = i; j < s.size(); ++j) {
            if (isPalindromes(i, j)) {
                an.push_back(s.substr(i, j - i + 1));
                dfs(j + 1);
                an.pop_back();
            }
        }
    }

    vector<vector<string> > partition(string s) {
        this->s = move(s);
        dfs(0);
        return ans;
    }
};
相关推荐
澈2077 分钟前
深入浅出C++滑动窗口算法:原理、实现与实战应用详解
数据结构·c++·算法
ambition2024237 分钟前
从暴力搜索到理论最优:一道任务调度问题的完整算法演进历程
c语言·数据结构·c++·算法·贪心算法·深度优先
cmpxr_39 分钟前
【C】原码和补码以及环形坐标取模算法
c语言·开发语言·算法
qiqsevenqiqiqiqi40 分钟前
前缀和差分
算法·图论
代码旅人ing1 小时前
链表算法刷题指南
数据结构·算法·链表
Yungoal1 小时前
常见 时间复杂度计算
c++·算法
6Hzlia1 小时前
【Hot 100 刷题计划】 LeetCode 48. 旋转图像 | C++ 矩阵变换题解
c++·leetcode·矩阵
不爱吃炸鸡柳2 小时前
单链表专题(完整代码版)
数据结构·算法·链表
CylMK2 小时前
题解:AT_abc382_d [ABC382D] Keep Distance
算法
Dfreedom.2 小时前
计算机视觉全景图
人工智能·算法·计算机视觉·图像算法