【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;
    }
};
相关推荐
kebijuelun几秒前
ERNIE 5.0:统一自回归多模态与弹性训练
人工智能·算法·语言模型·transformer
历程里程碑18 分钟前
普通数组----最大子数组和
大数据·算法·elasticsearch·搜索引擎·排序算法·哈希算法·散列表
52Hz11844 分钟前
力扣230.二叉搜索树中第k小的元素、199.二叉树的右视图、114.二叉树展开为链表
python·算法·leetcode
苦藤新鸡1 小时前
56.组合总数
数据结构·算法·leetcode
菜鸟233号1 小时前
力扣647 回文子串 java实现
java·数据结构·leetcode·动态规划
LiLiYuan.1 小时前
【Cursor 中找不到LeetCode 插件解决办法】
算法·leetcode·职场和发展
Charlie_lll1 小时前
力扣解题-[3379]转换数组
数据结构·后端·算法·leetcode
captain3761 小时前
Java队列(Queue)
算法·链表
TracyCoder1231 小时前
LeetCode Hot100(23/100)——142. 环形链表 II
算法·leetcode·链表