131. 分割回文串(回溯)

给定一个字符串 s,将 s 分割成一些子串,使每个子串都是回文串。

返回 s 所有可能的分割方案。

示例:

输入: “aab”
输出:
[
[“aa”,“b”],
[“a”,“a”,“b”]
]

分析:

相比前面的组合数的可能组合方案问题,在这里要对字符串进行分割,组合方案取决于字符串分割线的位置,代码如下:

class Solution {
    
    
public:
    vector<vector<string>> ret;
    vector<string> path;
    void backTracking(const string& s, int index){
    
    
        if(index >= s.size()){
    
    
            ret.push_back(path);
            return;
        }
        for(int i = index; i < s.size(); i++) {
    
    
            if(isPalindrome(s, index, i)){
    
    
                string str = s.substr(index, i - index + 1);
                path.push_back(str);
            }else continue;
            backTracking(s, i + 1);
            path.pop_back();
        }
    }
    bool isPalindrome(const string& s, int index, int end){
    
    
        for(int i = index, j = end; i < j; ++i, --j){
    
    
            if(s[i] == s[j]) continue;
            else return false;
        }
        return true;
    }
    
    vector<vector<string>> partition(string s) {
    
    
        backTracking(s, 0);
        return ret;
    }
};

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_34612223/article/details/113934883