• 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];
            
            
        }
    };




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

  • 相关阅读:
    DROP,TRUNCATE 和DELETE的区别
    工作手记之Cransoft
    Java输入输出流
    上海植物园
    eclipse中开发android程序时,打开layout配置文件eclipse关闭
    Android SDK 2.2 开发环境搭建
    Android读取电话薄中的电话号码
    Android模拟器大小
    工作手记之Cransoft(二)
    工作手记之Cransoft(三)
  • 原文地址:https://www.cnblogs.com/learnordie/p/4656935.html
Copyright © 2020-2023  润新知