• 132. Palindrome Partitioning II (String; DP)


    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]记录从i到j是否是Palindrome,还要用cut[i]存储到i位置位置最少的cut数

    class Solution {
    public:
        int minCut(string s) {
            int len = s.length();
            vector<vector<bool>> dp(len, vector<bool>(len, false));
            vector<int> cut(len,0);
            for(int i = 0; i < len; i++) dp[i][i]=true;
            for(int i = 1; i < len; i++){
                cut[i]=cut[i-1]+1;
                for(int j = 0; j < i; j++){ //traverse the length
                    if(s[i]==s[j]){
                        if(j==i-1) dp[j][i] = true;
                        else dp[j][i]=dp[j+1][i-1];
                        if(dp[j][i]){
                            if(j==0) cut[i]=0;
                            else cut[i]=min(cut[j-1]+1, cut[i]);
                        }
                    }
                }
            }
            return cut[len-1];
        }
    };
  • 相关阅读:
    java集合部分原材料
    java--Collection继承结构图
    java--类与类之间的关系
    java--BigDecimal类
    java--生成随机数
    java--枚举类型
    java--数字格式化
    Java--包装类型
    Java--StringBuffer和StringBuilder
    Java--String
  • 原文地址:https://www.cnblogs.com/qionglouyuyu/p/4905676.html
Copyright © 2020-2023  润新知