[Backtrack] [leetcode] Split palindrome string

topic:

Give you a string s, please split s into some substrings so that each substring is a palindrome string. Return all possible splitting schemes for s.

A palindrome is a string that is read both forward and backward.

Example 1:

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

source:

131. Split palindrome

Problem-solving ideas: backtracking

  • Recursive termination condition: cutting is complete
  • Recursive call condition: if the current palindrome
class Solution {
public:
    vector< vector<string> > ret;
    vector<string> part;
    vector< vector<string> > partition(string s) {
        back(s);
        return ret;
    }
    void back(const string& s) {
        int n = s.size();
        if (n == 0) { // 被切割完了退出
            ret.push_back(part);
            return;
        }
        for (int i = 0; i < n; i++) {
            // 判断前i+1个字符是否为回文,如果是则继续
            if (is(s, i+1)) {
                part.push_back(s.substr(0, i+1));
                back(s.substr(i+1));
                part.pop_back();
            }
        }
    }
    // 判断s的前n个字符是不是回文
    bool is(const string& s, int n) {
        for (int i = 0; i < n/2; i++) {
            if (s[i] != s[n-i-1]) {
                return false;
            }
        }
        return true;
    }
};

 

Guess you like

Origin blog.csdn.net/hbuxiaoshe/article/details/114976757