LeetCode 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.
题目分析:给出一个字符串,将该字符串分割,使得每部分都是回文串,求最小的额切割次数。

假设dp[i][j]表示s[i…j]的最小切割次数,则有

dp[i][j]=0s[i]!=s[j]min{dp[i][j],dp[i][k]+dp[k+1][j]+1}i=ji+1=jik<j

代码如下:

class Solution {
public:
     int minCut(string s) {
        int n = s.length();
        int dp[n][n];
        memset(dp,0,sizeof(dp));

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

        for(int len = 2; len <= n; len++)
        {
            for(int i = 0; i + len < n; i++)
            {
                int j = i + len;
                dp[i][j] = n;
                if(s[i] == s[j] && dp[i+1][j-1] == 0) dp[i][j] = 0;
                for(int k = i; k < j; k++)
                {
                    dp[i][j] = min(dp[i][j], dp[i][k] + dp[k+1][j] + 1);
                }
            }
        }


    return dp[0][n-1];
    }
};

结果,超时了。后来看了大神的代码,增加了一个数组,只用了O(n^2)的复杂度。
代码如下:

class Solution {
public:
    int minCut(string s) {
        int n = s.length();
        bool isPal[n][n];
        memset(isPal,0,sizeof(isPal));
        int cut[n];


        for(int j = 0; j < n; j++) {
            cut[j] = j;
            for(int i = 0; i <= j; i++) {
                if(s[i] == s[j] && (j - i <= 1 || isPal[i+1][j-1] == true) ) {
                    isPal[i][j] = true;

                    if(i > 0) {
                        cut[j] = min(cut[j],cut[i-1] + 1);
                    }
                    else {
                        cut[j] = 0;
                    }
                }
            }

        }

        return cut[n-1];
    }
};

对于每个cut[j],同样是将[0…j]分成两部分,只不过,其中一部分是回文子串。
这道题和Leetcode 279. Perfect Squares的技巧很相似。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhengjihao

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值