参考链接
http://blog.csdn.net/u011095253/article/details/9177451
http://blog.csdn.net/doc_sgl/article/details/13418125
题目描述
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"] ]
Palindrome Partitioning II
Given a string s, partition s such that every substring of the partition is a palindrome.
Return the minimum cuts needed for a palindrome partitioning of s.
For example, given s = "aab"
,
Return 1
since the palindrome partitioning ["aa","b"]
could be produced using 1 cut.
题目分析
class Solution {
public:
vector<vector<string> > partition(string s) {
vector<vector<string> > ret;
int size = s.size();
if(size == 0) return ret;
vector<vector<bool> > dp(size,vector<bool>(size,false));
//vector<vector<bool> > dp(size,vector<bool>(false)); 这里第一遍竟写错了。
for(int i = 0;i<size;i++)
{
dp[i][i] = true;
if(i<(size-1) && s[i]==s[i+1])
dp[i][i+1] = true;
}
//长度逐渐增加
for(int len = 3;len<=size;len++)
{
for(int i = 0;i+len<=size;i++)
{
int j = i+len-1;
if(dp[i+1][j-1] && s[i]==s[j])
dp[i][j] = true;
}
}
//递归
vector<string> tmp;
BFS(ret,s,dp,0,tmp);
return ret;
}
void BFS(vector<vector<string> > &ret,string s,vector<vector<bool> > &dp,int index,vector<string> &tmp)
{
if(index == s.size())
{
ret.push_back(tmp);
return;
}
for(int i = index;i<s.size();i++)
{
if(dp[index][i])
{
string str = s.substr(index,i-index+1);
//cout<<index<<","<<i<<":"<<str<<endl;
tmp.push_back(str);
BFS(ret,s,dp,i+1,tmp);
tmp.pop_back();
}
}
}
};
这个题是在上一个题的基础上继续问,返回所有分割中最小分割数
这个题很多人都分析过了,其实是两个合在一起的DP,其中一个DP绘制字符子串Palindrome矩阵,我们已经解决了。那么剩下的问题就是怎么求最小切数了
我们从字符串的尾巴往前推,我们来创造一个dp数组,叫cut[],在数组里cut[i] 表示从字符串第i位开始到字符串结尾需要切的刀数(包括该i位左边的一刀)
假设,不幸的是,从第i位开始到后面都不存在Palindrome,那么需要的刀数就为 len - i (包括左边的一刀),即每个字符间都要切一刀
那么我们从第i位开始,往后找,设计一个循环一直到字符串结尾,看是否存在Palindrome
- for(int j=i;j<len;j++){
- if (T[i][j]){
- cut[i] = Math.min(cut[i],1+cut[j+1]);
- }
- }
如果发现T[i][j]是一个Palindrome,那么从T[i][j]我们中间就不用切刀啦,然后去加上j位后面一位需要切刀的数量(+1是因为要保存最左边的一刀),然后我们和之前的cut[i]这一位进行比较,如果比之前的刀数少,我们便保留这个值,在循环到结尾的过程中一直最小值就能保证第i位以后的字串保持最小切刀数目,一直到cut[0]为止,最后因为第一个字符最左边不需要切,我们返回cut[0] - 1