回溯
class Solution {
public:
int cnt;
bool isPalindrome(const string& s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
if (s[i] != s[j]) {
return false;
}
}
return true;
}
void dfs(string s, int startIndex, int tempCnt){
if(startIndex==s.size()){
cnt = min(cnt, tempCnt-1);
return;
}
for(int i=startIndex;i<s.size();++i){
if(isPalindrome(s, startIndex, i)){ //[startIndex, i]是回文字串
dfs(s, i+1, tempCnt+1);
}
}
}
int minCut(string s) {
cnt = INT32_MAX;
dfs(s, 0, 0);
return cnt;
}
};
记忆回溯
class Solution {
public:
vector<int>dp;
bool isPalindrome(const string& s, int start, int end) {
for (int i = start, j = end; i < j; i++, j--) {
if (s[i] != s[j])
return false;
}
return true;
}
int dfs(string s, int startIndex){ //返回[startIndex, end]的最小分割次数
int minCnt = INT32_MAX;
for(int i=startIndex;i<s.size();++i){
if(isPalindrome(s, startIndex, i) ){ //[startIndex, i]是回文字串
if(i==s.size()-1){
dp[startIndex]=0;
return 0; //不用继续分割了,终止
}
if(dp[i+1]==-1) //没有递归记录过
dp[i+1]=dfs(s, i+1); //记录
minCnt = min(minCnt, dp[i+1]+1);
}
}
dp[startIndex] = minCnt;
return minCnt;
}
int minCut(string s) {
dp.resize(s.length(),-1);
int cnt = dfs(s, 0);
return cnt;
}
};