132. 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.
  • 这道题目花了半个小时的思考,用了大概半个小时就完成了可以pass的正确答案了,想来想去还是思路非常重要。如果找到递推公式就可以了。总的来说hard级别的dp算法还是比较难的,需要努力去做一番思考,才能得到正确的思路解题。hard级别的题目还是需要多思考,不过做题的速度变慢了许多。
  • 本题的解题思路先找到dp[i][j]代表字串(i-j)是否为回文字符串,cnt[i]代表(0..i)的最小剪切数量,则cnt[i] = min(cn[j-1]+1,cnt[i])(如果dp[i][j]为是,及字串(i…j)为回文字符串。
class Solution {
public:
    int minCut(string s) {
        int n = s.size();
        vector<bool> flag(n,false);
        vector<vector<bool>> dp(n,flag);

        vector<int> cnt(n,n+1);/*minCnt[i][j]the min cut number of [i-j]*/

        if(n <= 1){
            return 0;
        }

        for(int i = 0; i < n; ++i){
            dp[i][i] = true;
        }

        for(int k = 1; k < n; ++k){
            for(int l = 0;l+k < n; l++){
                if(s[l] == s[l+k]){
                    if(k == 1){
                        dp[l][l+k] = true;
                    }else{
                        dp[l][l+k] = dp[l+1][l+k-1];
                    }               
                }else{
                    dp[l][l+k] = false;
                }
            }
        }

        cnt[0] = 0;
        for(int i = 1;i < n; ++i){
            for(int j = i;j >= 0;j--){
                if(dp[j][i]){
                    if(j == 0){
                        cnt[i] = 0;
                    }else{
                        cnt[i] = min(cnt[i],cnt[j-1]+1);
                    }
                }
            }
        }

        return cnt[n-1];
        //find the min dp[i][j];    
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值