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) {
vector<vector<string> > res;
vector<string> solution;
helper(res, solution, s, 0);
return res;
}
void helper(vector<vector<string> >& res, vector<string>& solution,
const string& s, int i) {
if (i >= s.size()) {
res.push_back(solution);
return;
}
for (int j = i; j < s.size(); j++) {
if (!isPanlindrome(s, i, j))
continue;
solution.push_back(s.substr(i, j - i + 1));
helper(res, solution, s, j + 1);
solution.pop_back();
}
}
bool isPanlindrome(const string& str, int i, int j) {
while (i < j) {
if (str[i] != str[j])
return false;
i++;
j--;
}
return true;
}
};