今天陪女朋友的,一个特别单纯的女生,爱我特别深,因为她我哭了,她永远都会在我心里占有一席重要的位置!
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"] ]首先看看回文的字有什么特点,递归太神奇了
class Solution {
public:
vector<vector<string> > partition(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
vector<vector<string> > ret;
vector<string> strs;
int length=s.size();
if(length==0)
return ret;
if(length==1){
ret.push_back(vector<string>(1,s));
return ret;
}
vector<vector<string> > temp=partition(string(s.begin()+1,s.end()));
for(int i=0 ; i<temp.size() ; i++){
temp[i].insert(temp[i].begin(),string(1,s[0]));
}
ret.insert(ret.end(),temp.begin(),temp.end());
for(int i=2 ; i<=length ; i++){
string inner(s.begin(),s.begin()+i);
string rest(s.begin()+i,s.end());
if(JudgePalindrome(inner)){
strs.push_back(inner);
vector<vector<string> > intemp=partition(rest);
for(int j=0 ; j<intemp.size() ; j++){
intemp[j].insert(intemp[j].begin(),inner);
}
if(intemp.size()==0)
intemp.push_back(strs);
ret.insert(ret.end(),intemp.begin(),intemp.end());
}
strs.clear();
}
return ret;
}
bool JudgePalindrome(string s){
int length=s.size();
for(int i=0 ; i<length/2 ; i++){
if(s[i]!=s[length-i-1])
return false;
}
return true;
}
};