Leetcode 131. 分割回文串

dfs深搜回溯

class Solution {
public:
    vector<vector<string>> ans;
    vector<string> tmp;
    string str;
    bool is_P() {
        int i = 0, j = str.size() - 1;
        while (i < j) {
            if (str[i] == str[j]) ++i, --j;
            else return false;
        }
        return true;
    }
    void dfs(string &s, int index) {
        if (index == s.size() - 1) {
            str += s.back();
            if (is_P()) {
                tmp.push_back(str);
                ans.push_back(tmp);
                tmp.pop_back();
            }
            str.pop_back();
            return;
        }
        str += s[index];
        dfs(s, index + 1);
        if (is_P()) {
            tmp.push_back(str);
            str = "";
            dfs(s, index + 1);
            str = tmp.back();
            tmp.pop_back();
        }
        str.pop_back();
    }
    vector<vector<string>> partition(string s) {
        if (s.empty()) return ans;
        dfs(s, 0);
        return ans;
    }
};

你可能感兴趣的:(Leetcode 131. 分割回文串)