【Lintcode】136.Palindrome Partitioning

题目:

Given a string s, partition s such that every substring of the partition is a palindrome.

Return all possible palindrome partitioning of s.

Example

Given s = "aab", return:

[
  ["aa","b"],
  ["a","a","b"]
]

题解:

Solution 1 ()

class Solution {
public:
    vector<vector<string>> partition(string s) {
        if (s.empty()) {
            return {{}};
        }
        vector<vector<string> > res;
        vector<string> v;
        dfs(res, v, s, 0);
        
        return res;
    }
    void dfs(vector<vector<string> > &res, vector<string> &v, string s, int pos) {
        if (pos >= s.size()) {
            res.push_back(v);
            return;
        }
        string str;
        for (int i = pos; i < s.size(); ++i) {
            str += s[i];
            if (isValid(str)) {
                v.push_back(str);
                dfs(res, v, s, i + 1);
                v.pop_back();
            }
        }
    }
    bool isValid(string str) {
        if (str.empty()) {
            return true;
        }
        int begin = 0;
        int end = str.size() - 1;
        for (; begin <= end; ++begin, --end) {
            if (str[begin] != str[end]) {
                return false;
            }
        }
        return true;
    }
};

Solution 1.2 ()

class Solution {
public:
    bool isPalindrome(string &s, int i, int j){
        while(i < j && s[i] == s[j]){
            i++;
            j--;
        }
        if(i >= j) {
            return true;
        } else {
            return false;
        }
    }
    void helper(vector<vector<string>> & res, vector<string> &cur, string &s, int pos){
        if(pos == s.size()){
            res.push_back(cur);
            return;
        }
        for(int i = pos; i <= s.size() - 1; i++){
            if(isPalindrome(s, pos, i)){
                cur.push_back(s.substr(pos, i - pos + 1));
                helper(res, cur, s, i+1);
                cur.pop_back();
            }
        }
    }
    vector<vector<string>> partition(string s) {
        vector<vector<string>> res;
        vector<string> cur;
        helper(res, cur, s, 0);
        
        return res;
    }
};

 

posted @ 2017-05-17 21:24  Vincent丶丶  阅读(230)  评论(0编辑  收藏  举报