# LeetCode131: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"]
]
解题思路：
这道题跟Word Break II这道基本一样，需要用DP+DFS解决

dp[i-2]…dp[1],dp[0]进行求解。

unordered_map<int, vector<int> >求得后，接下来是采用DFS算法进行结果重构，如代码执行结果图，当长度为3时，有一种切割方案，即在长度为2的位置进行切割，然后长度为2的切割方案又有两种0和1，长度为1时，切割方案都为0，所以采用DFS时，遍历顺序为2，0然后获得一种结果，之后回溯到2,1，因为1的切割方案为0，所以为3,1,0，又是一种结果。

#include <iostream>
#include <vector>
#include <iterator>
#include <unordered_map>
#include <string>
#include <algorithm>

using namespace std;
/*
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:
//DP
vector<vector<string>> partition(string s) {
vector<vector<string>> retvec;
if(s.size() == 0)
return retvec;
int len = s.size();
vector<bool> dp(len+1, false);//前i个字符是否为回文数
dp[0] = true;
unordered_map<int, vector<int>> hashtable;//对前i个字符，如果其为回文数时的切分点
for(int i = 1; i <= len; i++)
{
vector<int> tmpv;
for(int j = 0; j < i; j++)
{
if(dp[j] && isPalindrome(s.substr(j, i-j)) )
{
dp[i] = true;
tmpv.push_back(j);

}
}
hashtable[i] = tmpv;
}

for(int k = 1; k <= len; k++)
{
vector<int> tvec = hashtable[k];
cout<<k<<":";
copy(tvec.begin(), tvec.end(), ostream_iterator<int>(cout, " "));
cout<<endl;
}
vector<int> curvec;
getResult(retvec, hashtable, s, len, curvec);
return retvec;

}
bool isPalindrome(string s)
{
int len = s.size();
if(len == 0)
return false;
for(int i = 0; i <= len/2; i++)
if(s[i] != s[len-i-1])
return false;
return true;
}

//DFS
void getResult(vector<vector<string>> &retvec, unordered_map<int, vector<int>> &hashtable, string &s, int len, vector<int> &curvec)
{
if(len == 0)
{
vector<string> tv;
int start = curvec.back();
for(int i = curvec.size()-2; i >= 0; i--)
{
int c = curvec[i];
tv.push_back(s.substr(start, c-start));
start = c;
}
tv.push_back(s.substr(curvec[0]));
retvec.push_back(tv);
return ;
}
vector<int> tmpv = hashtable[len];
vector<int>::iterator iter;
for(iter = tmpv.begin(); iter != tmpv.end(); ++iter)
{
curvec.push_back(*iter);
getResult(retvec, hashtable, s, *iter, curvec);
curvec.pop_back();

}

}
};

int main(void)
{
string s("aab");
Solution solution;
vector<vector<string>> retvv = solution.partition(s);
vector<vector<string>>::iterator iter;
for(iter = retvv.begin(); iter != retvv.end(); ++iter)
{
vector<string>::iterator it;
for(it = (*iter).begin(); it != (*iter).end(); ++it)
cout<<*it<<" ";
cout<<endl;
}

return 0;
}

-----------------------我和我追猪的梦-----------------------------------------------------------------

posted @ 2014-04-23 16:54  mickole  阅读(223)  评论(0编辑  收藏  举报