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"] ]
本题为分割得到所有回文字符串,采用DFS即可
class Solution {
public:
vector<vector<string>> partition(string s) {
vector<vector<string>> res;
if(s.empty()) return res;
vector<string> temp;
dfs(res,temp,0,s);
return res;
}
void dfs(vector<vector<string>>& res,vector<string>& temp,int index,string& s){
if(index==s.size()){
res.push_back(temp);
return;
}
for(int i=index;i<s.size();i++){
if(Palin(s,index,i)){
temp.push_back(s.substr(index,i-index+1));
dfs(res,temp,i+1,s);
temp.pop_back();
}
}
}
bool Palin(const string &s,int start,int end){
while(start<=end){
if(s[start++]!=s[end--])
return false;
}
return true;
}
};
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.
在第二题中,再采用DFS会超时,因为第二题只需要求最小的切割数,而第一题是求所有的切割,有许多切割的切割数相同或者超过了,即使剪枝了也还是会超时
本题用到DP动态规划
步骤1 找到递推公式,假设bool dp[i][j]表示字符串下标从i到j是否为回文串 则dp[i][j]=(s[i]==s[j])&&((j-i>=1)||s[i+1][j-1])
如果i到j是回文的话,他依赖于i+1,j-1也为回文。而计算切割数的count数组,count[i]=min(1+count[j+1],count[i]),count[i]
代表从i开始的字符串的切割数
步骤2 确定循环顺序,因为j始终大于i,所以count[i]依赖于count[j],所以i的循环是逆序。
class Solution {
public:
int minCut(string s) {
vector<vector<int>> dp(s.size(),vector<int>(s.size(),0));
vector<int> count(s.size()+1,0);
for(int i=s.size()-1;i>=0;i--){
count[i]=INT_MAX;
for(int j=i;j<s.size();j++){
if(s[i]==s[j]&&((j-i)<=1||dp[i+1][j-1])){
dp[i][j]=1;
count[i]=min(1+count[j+1],count[i]);
}
}
}
return count[0]-1;
}
};