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"]]
Solution 1:
分析:
根据题目我们不难得出:
任何长度不为零的字符串都至少有一个符合题意的划分
因此,每一个字符串可以分为两部分,1:从首字符开始的一段回文;2:除去这一部分的后一段字符串(不要求回文);
采用递归的思想,对一段字符串从首字符进行遍历,如果是回文,则用相同的函数得到 后一段字符串 的多个划分,再与之前的回文相连,由此得到这一段字符串的划分。
(对于line 16的一点说明:当目标字符串本身是回文时,它本身也算是自己的一个有效的划分。)
代码:
class Solution {
public:
vector<vector<string>> comb(string f,vector<vector<string>> e){//连接函数//首段回文串 + 尾端的所有划分,即对于每个首段回文的所有划分
for(int i=0;i<e.size();i++){
e[i].insert(e[i].begin(),f);
}
return e;
}
vector<vector<string>> partition(string s) {//递归函数,得到s的所有划分
vector<vector<string>> ans;
int l=s.length();
string head,end;
for(int i=1;i<=l;i++){
head.assign(s,0,i);
if(ispd(head)){
if(i==l){
vector<string> h;
h.push_back(head);
ans.push_back(h);
break;
}
end.assign(s,i,l-i);
vector<vector<string>> way =comb(head,partition(end));
ans.insert(ans.end(),way.begin(),way.end());
}
}
return ans;
}
bool ispd(string s){//判断s是否为回文
int l = s.length();
for(int i=0;i<(l+1)/2;i++){
string f(s,i,1);
string e(s,l-1-i,1);
if(f!=e)
return false;
}
return true;
}
};