131. Split palindrome (backtracking)

Given a string s, split s into some substrings so that each substring is a palindrome.

Return all possible splitting schemes for s.

Example:

Input: "aab"
Output:
[
["aa","b"],
["a","a","b"]
]

analysis:

Compared with the previous possible combination scheme problem of the number of combinations, the string is divided here, and the combination scheme depends on the position of the string dividing line. The code is as follows:

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;
    }
};

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_34612223/article/details/113934883