palindrome-partitioning

来源:互联网 发布:多个表格数据汇总公式 编辑:程序博客网 时间:2024/06/16 02:57

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”]
]

首先可以在O(n^2)的时间复杂度内构造二维数组ispal[i][j]判断是否string 从i到j是否是回文子串.
之后利用DFS直接暴力排列.

class Solution {public:   vector<vector<string>> partition(string s) {    if (s.size() <= 1)        return vector<vector<string>>{vector<string>{s}};    int len = s.size();    vector<vector<int>> ispal(len, vector<int>(len, 0));    vector<vector<string>> res;    vector<string> temp;    for (int i = 0; i<len; ++i)    {        ispal[i][i] = 1;        if (i + 1<len&&s[i] == s[i + 1])            ispal[i][i + 1] = 1;    }    for (int i = 0; i<len; ++i)    {        for (int j = 0; j<len; ++j)        {            if (j - 1 >= 0 && j + i + 1<len&&ispal[j][j + i] == 1&&s[j-1]==s[j+i+1])                ispal[j - 1][j + i + 1] = 1;        }    }    recurfind(s, 0, len - 1, res, temp, ispal);    return res;}void recurfind(string s, int begin, int end, vector<vector<string>>& res, vector<string>& temp, vector<vector<int>>& ispal){    if (begin>end)    {        res.push_back(temp);    }    for (int i = begin; i <= end;)    {        if (ispal[begin][i])        {            temp.push_back(s.substr(begin, i - begin + 1));            recurfind(s, i + 1, end, res, temp,ispal);        }        ++i;    }    if (!temp.empty())        temp.pop_back();}};
0 0