题目:
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>> res;
vector<string> cmb;
int len;
bool isPalindrome(string& s,int begin,int end){
while(begin<end){
if(s[begin]!=s[end]){
return false;
}
begin++;
end--;
}
return true;
}
void partition(int curPos,string& s){
if(curPos==len){
res.push_back(cmb);
}
else{
for(int i=curPos;i<len;i++){
if(isPalindrome(s,curPos,i)){
cmb.push_back(s.substr(curPos,i-curPos+1));
partition(i+1,s);
cmb.pop_back();
}
}
}
}
vector<vector<string>> partition(string s) {
len=s.size();
if(len==0){
return res;
}
partition(0,s);
return res;
}
};