【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;
    }
};
相关推荐
ZoeJoy817 分钟前
算法筑基(二):搜索算法——从线性查找到图搜索,精准定位数据
算法·哈希算法·图搜索算法
Alicx.22 分钟前
dfs由易到难
算法·蓝桥杯·宽度优先
_日拱一卒33 分钟前
LeetCode:找到字符串中的所有字母异位词
算法·leetcode
云泽8081 小时前
深入 AVL 树:原理剖析、旋转算法与性能评估
数据结构·c++·算法
Wilber的技术分享2 小时前
【LeetCode高频手撕题 2】面试中常见的手撕算法题(小红书)
笔记·算法·leetcode·面试
邪神与厨二病2 小时前
Problem L. ZZUPC
c++·数学·算法·前缀和
梯度下降中3 小时前
LoRA原理精讲
人工智能·算法·机器学习
IronMurphy3 小时前
【算法三十一】46. 全排列
算法·leetcode·职场和发展
czlczl200209253 小时前
力扣1911. 最大交替子序列和
算法·leetcode·动态规划
靴子学长4 小时前
Decoder only 架构下 - KV cache 的理解
pytorch·深度学习·算法·大模型·kv