随笔 - 112  文章 - 0  评论 - 0  阅读 - 1426

分割回文串(回溯)

给你一个字符串 s,请你将 s 分割成一些子串,使每个子串都是回文串。返回 s 所有可能的分割方案。

示例 1:

输入:s = "aab"
输出:[["a","a","b"],["aa","b"]]

示例 2:

输入:s = "a"
输出:[["a"]]
复制代码
class Solution {
public:
    vector<vector<string>> res;
    vector<string> temp;
    bool check(string s){
        int start=0;
        int end = s.size()-1;
        while(start<=end){
            if(s[start]!=s[end]){
                return false;
            }
            start++;
            end--;
        }
        return true;
    }
    void backtrack(string s,int start,int end){
        if(start>end){
            res.push_back(temp);
            return;
        }
        //分别截取长度为1,2,3...的子串进行验证,成功则用剩下的部分递归
        for(int i=1;i<=end-start+1;i++){
            if(check(s.substr(start,i))){//判断子串是否为回文串
                temp.push_back(s.substr(start,i));
                backtrack(s,start+i,end);
                temp.pop_back();
            }
        }
    }
    vector<vector<string>> partition(string s) {
        backtrack(s,0,s.size()-1);
        return res;
    }
};
复制代码

 

posted on   _月生  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具
· Manus的开源复刻OpenManus初探
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示