• 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.

    Solution:

    Compare with 131. Palindrome Partitioning, this is a DP problem. In order to pass the OJ, there are two DP, the first one is the initialization of the table, it records if from i to j is a palindrome.

    class Solution {
    public:
        int minCut(string s) {
            if(s.empty()){
                return 0;
            }
            int size = s.size();
            // size * size table
            // i to j is a palindrome or not
            vector<vector<bool>> table(size, vector<bool>(size, false));
            initialize(table, s);
            vector<int> dp(size + 1);
            for(int i = 0; i <= size; i++){
                dp[i] = i - 1;
            }
            for(int i = 1; i <= size; i++){
                for(int j = 0; j < i; j++){
                    if(table[j][i - 1]){
                        dp[i] = min(dp[i], dp[j] + 1);
                    }
                }
            }
            return dp[size];
        }
    private:
        void initialize(vector<vector<bool>>& table, string s){
            for(int i = 0; i < s.size(); i++){
                table[i][i] = true;
            }
            for(int i = 0; i < s.size() - 1; i++){
                table[i][i + 1] = s[i] == s[i + 1];
            }
            for(int i = s.size() - 1; i >= 0; i--){
                for(int j = i + 2; j < s.size(); j++){
                    table[i][j] = table[i + 1][j - 1] && s[i] == s[j];
                }
            }
            return;
        }
    };
  • 相关阅读:
    洛谷7月月赛 B 题解
    undone
    树剖学习
    关于两周后noip---小计划
    线段树技巧练习--GSS1
    链式前向星存图及注意要点
    错题集合
    树上差分问题
    2020暑假学习内容整理及后续计划
    安利大佬博客
  • 原文地址:https://www.cnblogs.com/wdw828/p/6834704.html
Copyright © 2020-2023  润新知