LeetCode 132. Palindrome Partitioning II

来源:互联网 发布:win7电脑摄像头软件 编辑:程序博客网 时间:2024/05/22 03:31

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的技巧很相似。

原创粉丝点击