131. Palindrome Partitioning回溯算法

来源:互联网 发布:2016网络十大洗脑神曲 编辑:程序博客网 时间:2024/05/17 22:51

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

Subscribe to see which companies asked this question

分析:

回溯算法,每次增长一个长度检验是否为回文数。

经典解法。

class Solution {
public:
    bool check(string s)
    {
        int i=0;
        int j=s.size()-1;
        while(i<j)
        {if(s[i]!=s[j]) return false;++i;--j;}
        return true;
    }
    void build(string s,int t,vector<vector<string>> &v1,vector<string> v2)
    {
        if(t==s.size()){v1.push_back(v2);}
        else
        {
            string s1="";
            for(int i=t;i<s.size();++i)
            {
                s1+=s[i];
                v2.push_back(s1);
                if(check(s1)) {build(s,i+1,v1,v2);}
                v2.pop_back();
            }
        }
    }
    vector<vector<string>> partition(string s) {
        vector<vector<string>> v1;
        vector<string> v2;
        if(s.size()==0) return v1;
        string s1="";
        for(int i=0;i<s.size();++i)
        {
            s1+=s[i];
            v2.push_back(s1);
            if(check(s1)) { build(s,i+1,v1,v2);}
            v2.pop_back();
        }
        return v1;
    }
};

0 0
原创粉丝点击