Palindrome Partitioning
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) {
if (s.empty()||s.size()==0) return {};
vector<vector<string>>ans;
vector<string>path;
pal(s,0,s.size(),ans,path);
return ans;
}
void pal(string &s,int begin,int end,vector<vector<string>>&ans,vector<string>&path)
{
if (begin==s.size())
{
ans.push_back(path);
return ;
}
for (int i=begin; i<end; i++)
{
string temp=s.substr(begin,i-begin+1);
reverse(temp.begin(),temp.end());
if (temp==(s.substr(begin,i-begin+1)))
{
path.push_back(temp);
pal(s,i+1,end,ans,path);
path.pop_back();
}
}
return ;
}
};