c_cpp [dfs] [string]回文分区

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp [dfs] [string]回文分区相关的知识,希望对你有一定的参考价值。

/*
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
For example, given s = "aab",
Return
  [
    ["aa","b"],
    ["a","a","b"]
  ]
*/


bool is_palindrome(const string& s) {
    if(s.empty()) return true;
    int low = 0, high = s.size()-1;
    while(low <= high) {
        if(s[low] != s[high]) return false;
        low++;
        high--;
    }
    return true;
}

void dfs(vector<vector<string>>& res, vector<string> one_part, const string& s, int begin) {
    if(begin == s.size()) {
        res.push_back(one_part);
        one_part.clear();
        return;
    }
    for(int j=begin; j<s.size(); j++) {
        string left = s.substr(begin, j-begin+1);
        if(is_palindrome(left) == false) continue;
        one_part.push_back(left);
        dfs(res, one_part, s, j+1); // j+1 not j
        one_part.pop_back();
    }
}

vector<vector<string>> find_partitions(const string& s) {
    vector<vector<string>> res;
    vector<string> part;
    dfs(res, part, s, 0);
    return res;
}

int main()
{
    vector<vector<string>> res = find_partitions("abaab");
    for(auto a : res) {
        for(auto s : a) cout << s << " ";
        cout << endl;
    }
}

以上是关于c_cpp [dfs] [string]回文分区的主要内容,如果未能解决你的问题,请参考以下文章

java 131.回文分区(#1 DFS).java

java 131.回文分区(#1 DFS).java

java 131.回文分区(#1 DFS).java

java 131.回文分区(#1 DFS).java

java 131.回文分区(#1 DFS).java

java 131.回文分区(#1 DFS).java