Palindrome Partitioning II 分类: Leetcode(动态规划) 2015-04-14 11:01 22人阅读 评论(0) 收藏

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.


f(i,j) 表示[i,j]之前最小的cut数,状态转移方程:
f(i,j) = min{f(i,k) + f(k+1,j)}   i<=k<=j, 0<=i <=j <n
这是一个二维函数,所以我们转化为一维DP
f(i) 表示[i, n-1] 之间最小的cut数, n为字符串长度,则状态转移方程为
f(i) = min {f(j+1) +1} , i<=j < n

判断[i,j]是否是回文
P[i,j] = true if [i,j]是回文, 那么
P[i][j] = str[i] == str[j] && P[i+1][j-1]

class Solution {
public:
    int minCut(string s) {
        const int n = s.size();
        int f[n+1];
        bool p[n][n];
        fill_n(&p[0][0], n*n, false);
        for (int i = 0; i <=n; i++) {
            f[i] = n-1-i;
        }
        
        for (int i = n-1; i >=0; i--) {
            for (int j = i; j < n; j++) {
                if (s[i] == s[j] && (j-i < 2 || p[i+1][j-1])) {
                    p[i][j] = true;
                    f[i] = min(f[i], f[j+1]+1);
                }
            }
        }
        return f[0];
        
        
    }
};




版权声明:本文为博主原创文章,未经博主允许不得转载。

原文地址:https://www.cnblogs.com/learnordie/p/4656935.html