Leetcode 131. Palindrome Partitioning (Medium) (cpp)

来源:互联网 发布:powerdvd源码输出 编辑:程序博客网 时间:2024/06/05 10:24

Leetcode 131. Palindrome Partitioning (Medium) (cpp)

Tag: Backtracking

Difficulty: Medium


/*131. Palindrome Partitioning (Medium)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"]]*/class Solution {public:    vector<vector<string>> partition(string s) {        int _size = s.size();        vector<vector<bool>> t(_size, vector<bool>(_size, false));        for (int j = 0; j < _size;j++) {            for (int i = 0; i < _size;i++) {                if (i + j < _size) {                    if (j == 0) {                        t[i][i + j] = true;                    } else if (j < 3) {                        t[i][i + j] = (s[i] == s[i + j]);                    } else {                        t[i][i + j] = (s[i] == s[i + j]) && (t[i + 1][i + j - 1]);                    }                }            }        }        vector<vector<string>> res;        vector<string> res_sub;        partition(res, res_sub, t, 0, s);        return res;    }private:    void partition(vector<vector<string>>& res, vector<string>& res_sub, const vector<vector<bool>>& t, int index, const string& s) {        if (index == t[0].size()) {            res.push_back(res_sub);            return;        }        for (int i = index; i < t[0].size(); i++) {            if (t[index][i]) {                res_sub.push_back(s.substr(index, i - index + 1));                partition(res, res_sub, t, i + 1, s);                res_sub.pop_back();            }        }    }};


0 0
原创粉丝点击