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.
第一次排到hard,做了很久,答案虽然正确,但是TLE了。以下是博主的代码,使用迭代法,效率低,强烈不推荐。
class Solution {
public:
int minCut(string s) {
layer = 0;
result.clear();
itercut(s);
return minvec(result);
}
void itercut(string s){
layer++;
if(isPalindrome(s)){
layer--;
result.push_back(layer);
return;
}
for(int i = 1; i < s.length(); i++){
string first(s, 0, i);
string last(s, i);
if(isPalindrome(first)){
if(isPalindrome(last)){
result.push_back(layer);
continue;
} else{
itercut(last);
continue;
}
} else{
continue;
}
}
layer--;
return;
}
bool isPalindrome(string s){
string inv = s;
reverse(inv.begin(),inv.end());
if(s == inv){
return true;
} else{
return false;
}
}
int minvec(vector<int> v){
int tmp = INT_MAX;
for(int i = 0; i < v.size(); i++){
if(v[i] < tmp)
tmp = v[i];
}
return tmp;
}
protected:
int layer;
vector<int> result;
};
博主迭代法的思想就是参考了之前Sum II的题目,就是一层一层的遍历,算法时间复杂度很高,下面的代码不是最快的,但是性能也还可以,思路可以参考和借鉴:
class Solution {
public:
int minCut(string s) {
int n = s.size();
vector<vector<bool> > isPalin(n, vector<bool>(n, false));
vector<int> min(n+1, -1); //min cut from end
for(int i = 0; i < n; i ++)
{
isPalin[i][i] = true;
}
for(int i = n-1; i >= 0; i --)
{
min[i] = min[i+1] + 1;
for(int j = i+1; j < n; j ++)
{
if(s[i] == s[j])
{
if(j == i+1 || isPalin[i+1][j-1] == true)
{
isPalin[i][j] = true;
if(j == n-1)
min[i] = 0;
else if(min[i] > min[j+1]+1)
min[i] = min[j+1] + 1;
}
}
}
}
return min[0];
}
};
从后往前构造二维数组isPalin,用于存储已经确定的回文子串。isPalin[i][j]==true代表s[i,…,j]是回文串。
在构造isPalin的同时使用动态规划计算从后往前的最小切分数,记录在min数组中。min[i]代表s[i,…,n-1]的最小切分数。
(上述两步分开做会使得代价翻倍,容易TLE)
关键步骤:
1、min[i]初始化为min[i+1]+1,即初始化s[i]与s[i+1]之间需要切一刀。这里考虑边界问题,因此min数组设为n+1长度。
2、从i到n-1中间如果存在位置j,同时满足:(1)s[i,…,j]为回文串;(2)1+min[j+1] < min[i]。
那么min[i]=1+min[j+1],也就是说一刀切在j的后面比切在i的后面要好。