问题描述:
Given a string s, partition s such that every substring of the partition is a palindrome.
Return all possible palindrome partitioning of s.
示例, given s = "aab"
,
Return
[ ["aa","b"], ["a","a","b"] ]
问题分析:
此类问题属于回溯法范畴,对每次取出的子串判断是否是回文的,若全都是,则把这些字串放入到res中,否则不作处理。
过程详见代码:
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>>res;
vector<string> re;
bl(res,re,0,s,s.length());
return res;
}
void bl(vector<vector<string>>&res, vector<string>& re, int start, string s,int left)
{
if (!left)
{
res.push_back(re);
return;
}
for (int i = 1; i <= left; i++)
{
string t = s.substr(start, i);
if (!palindrome(t)) continue;
re.push_back(t);
bl(res, re, start + i, s, left - i);
re.pop_back();
}
}
bool palindrome(string s)
{
for (int i = 0; i < s.length() / 2; i++)
{
if (s[i] != s[s.length() - 1 - i]) return false;
}
return true;
}
};