题目:
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"] ]
思路:
利用动态规划DP的思路做,过程类似于
http://blog.csdn.net/lanxu_yy/article/details/17310247。惟一的区别是在word break中检查word是否符合要求与检查palindrome不同。
代码:
class Solution {
public:
vector<bool>* dp;
vector<vector<string>> result;
vector<string> str;
vector<vector<string>> partition(string s) {
if(s.size()>0)
{
dp = new vector<bool>[s.size()];
for(int i=0;i<s.size();i++)
{
for(int j=i;j<s.size();j++)
{
dp[i].push_back(isPalindrome(s,i,j));
}
}
output(s, s.size()-1);
}
return result;
}
void output(string s, int k)
{
if(k<0)
{
vector<string> tmp;
for(int i=str.size()-1;i>=0;i--)
{
tmp.push_back(str[i]);
}
result.push_back(tmp);
}
else
{
for(int i=0;i<=k;i++)
{
if(dp[i][k-i])
{
str.push_back(s.substr(i,k-i+1));
output(s, i-1);
str.pop_back();
}
}
}
}
bool isPalindrome(string s, int i, int j)
{
for(;i<j;i++,j--)
{
if(s[i]!=s[j])
{
return false;
}
}
return true;
}
};