qingcheng奕  

https://oj.leetcode.com/problems/palindrome-partitioning/

给定一个字符串 s,求所有的子串组合,每个子串都是回文的。

比如,aba: {a,b,a},{aba}

对于这类问题(对一个串的划分)基本上就是用递归。

首先设一个 record 数组,记录中间结果,省的多次计算。

 

class Solution {
public:
    vector<vector<string> > partition(string s) {
        vector<vector<string> > ans;
        if(s.empty())
            return ans;
        const size_t len = s.size();

        vector<vector<bool> > flag;
        flag.resize(len);
        for(int i = 0;i<len;i++)
            flag[i].resize(len);

        for(int i = 0;i<len;i++)
            for(int j = i;j<len;j++)
            {
                flag[i][j] = isPal(s,i,j);
            }

        vector<string> ansPiece;
        sub(0,flag,ans,ansPiece,s);
        return ans;
    }
    void sub(int begin,vector<vector<bool> > &flag,vector<vector<string> > &ans,vector<string> &ansPiece,string &s)
    {
        if(begin == s.size())
        {
            vector<string> _ansPiece = ansPiece;
            ans.push_back(_ansPiece);
            return ;
        }

//here i means end position
for(int i = begin;i<flag.size();i++) { string tempstr; if(flag[begin][i]) { tempstr = s.substr(begin,i-begin+1); ansPiece.push_back(tempstr); sub(i+1,flag,ans,ansPiece,s); ansPiece.pop_back(); } } } bool isPal(string s,int i,int j) { if(i==j) return true; int temp = 0; while(i+temp<j-temp) { if(s[i+temp]!=s[j-temp]) return false; temp++; } return true; } };

 

posted on 2014-07-03 19:40  qingcheng奕  阅读(209)  评论(0编辑  收藏  举报