题目:
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"] ]
思路:我们从第一个字符开始直到最后一个字符,一旦有可以构造成回文的字符串,继续判断剩下的字符串是否可以构造成回文字符串。直到真个字符串都构造结束,输出构成的方式。使用一个向量记录构成的方式。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
bool check(string& str,int begin,int end)
{
int i = begin ;
int j = end;
for(;i<=j;i++,j--)
if(str[i] != str[j])
return false;
return true;
}
void helper(string& str,int begin,int end,vector<int>& pos)
{
int i,j,k;
if(begin > end)
{
for(j=0;j<pos.size();j++)
{
cout<<str[j];
if(pos[j] != -1)
{
cout<<",";
pos[j] = -1;
}
}
cout<<endl;
}
for(i= begin;i<=end;i++)
{
if(check(str,begin,i))
{
pos[i] = i-begin+1;
helper(str,i+1,end,pos);
}
}
}
void PalindromePartition(string& str)
{
if(str.length() == 0)
return ;
vector<int> pos(str.length(),-1);
helper(str,0,str.length()-1,pos);
}
int main()
{
string str("aab");
PalindromePartition(str);
system("pause");
return 0;
}
这也是一个典型的回溯问题,但是有的同学可能认为什么没有发现pos发生回溯的现象,也就是恢复原状的现象呢,因为在传递pos数组时传递的是已经分配好空间的数组,这个关于回溯使用这种方案,可以参考数据结构与算法系列中矩阵走的路径那个问题。