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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值