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"] ]深搜加回溯,从i到j如果是回文,将s[i,j]加入临时切分结果,继续判断从j开始的回文分割。
class Solution {
public:
vector<vector<string>> partition(string s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
vector<vector<string>> result;
vector<string> temp;
if(s.length() == 1) {
temp.push_back(s);
result.push_back(temp);
return result;
}
recursivePair(s,0,temp,result);
return result;
}
void recursivePair(string s, int start, vector<string> temp, vector<vector<string>> &result) {
if(start == s.length()) {
result.push_back(temp);
}
for(int i = start; i < s.length(); i++) {
if(isPalindrome(s,start,i)) {
temp.push_back(s.substr(start,i+1-start));
recursivePair(s,i+1,temp,result);
temp.pop_back();
}
}
}
bool isPalindrome(string s,int start, int end) {
if(start == end) return true;
for(int i = start, j = end; i < j; i++,j--) {
if(s[i] != s[j]) return false;
}
return true;
}
};