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;
    }
};
原文地址:https://www.cnblogs.com/wdw828/p/6834704.html