LeetCode-Palindrome Partitioning-回文分割

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

这个题目很简单。递归搜索+枚举就能过,只要注意递归到0时,压入一个空数组即可。

class Solution {
public:
    int n;
    string s;
    bool Check(int p,int q){
        int l=p;
        int r=q-1;
        while(l<r){
            if (s[l]!=s[r]){return false;}
            l++;
            r--;
        }
        return true;
    }
    vector<vector<string>> Solve(int p){
        vector<vector<string>> res;
        if (p==0){
            res.push_back(vector<string>());
            return res;
        }
        for (int i=0;i<p;i++){
            if (Check(i,p)){
                vector<vector<string>> ret=Solve(i);
                string cur=s.substr(i,p-i);
                for (int i=0;i<ret.size();i++){
                    res.push_back(ret[i]);
                    res[res.size()-1].push_back(cur);
                }
            }
        }
        return res;
    }
    vector<vector<string>> partition(string s) {
        n=s.length();
        this->s=s;
        return Solve(n);
    }
};

  

posted @ 2014-10-08 17:44  zombies  阅读(107)  评论(0编辑  收藏  举报