132. 分割回文串 II

回溯

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;
    }   
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值