LeetCode: 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.

For example, given s = "aab",
Return

  [
    ["aa","b"],
    ["a","a","b"]
  ]
对于这类返回所有结果集合的问题,通常都是使用DFS,递归算法
Soluton:
class Solution {
public:
 
    bool valid(string &str, int st, int end){
        while (st < end){
            if (str[end] != str[st]){
                return false;
            }else{
                st++;
                end--;
            }
        }
        return true;
    }
     
    void find(string &s, int st, vector<string> &res, vector<vector<string> > &resAll){
        if (st>=s.size()){
            resAll.push_back(res);
        }else{
        for (int i=st;i<s.size();i++){            
            if (valid(s,st,i)){
                res.push_back(s.substr(st,i-st+1));
                find(s,i+1,res,resAll);        
                res.pop_back();
            }          
        }
        }  
    }
 
    vector<vector<string>> partition(string s) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        vector<vector<string> > resAll;
        vector<string> res;
        find(s,0,res,resAll);
        return resAll;    
    }
};

 

posted @ 2014-04-06 15:13  andyqee  阅读(155)  评论(0)    收藏  举报