【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;
    }
};
相关推荐
地平线开发者30 分钟前
模型部署|如何解决算子约束
深度学习·算法·自动驾驶
Navigator_Z1 小时前
LeetCode //C - 1254. Number of Closed Islands
c语言·算法·leetcode
deepseek231 小时前
GPT-6 Astra 破解 FrontierMath 九年悬案拆解:调和熵投票规则反证核恒非空,局部搜索如何终结反例悬赏
人工智能·算法·ai agent
syagain_zsx1 小时前
算法基础篇 · 04 前缀和(C++ 题解)
c++·算法·前缀和
青山是哪个青山3 小时前
LeetCode 123:买卖股票的最佳时机 III
算法
Zane19943 小时前
写对二分查找有多难?Java集合框架的作者也曾栽在一行mid计算上
算法
Lokey8683 小时前
transformer结构
算法
罗斯8393 小时前
EMBER恶意软件基准数据集
人工智能·算法·安全·网络安全
0+1113 小时前
算法 --二分查找
c++·算法·leetcode
圣保罗的大教堂3 小时前
leetcode 1674. 使数组互补的最少操作次数 中等
leetcode