132. Palindrome Partitioning II

本文介绍了一种使用动态规划解决字符串最小切割数问题的方法。通过维护两个状态:是否构成回文串及最小切割次数,实现了高效求解。具体算法包括两部分关键步骤:判断回文性和更新最小切割数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一开始还用上一题的方法一定超时了,没想到,dp还是难,要2刷和理解
Calculate and maintain 2 DP states:
1.
pal[i][j] , which is whether s[i..j] forms a pal
2.
3.
d[i], which
is the minCut for s[i..n-1]
4.
Once we comes to a pal[i][j]==true:
• if j==n-1, the string s[i..n-1] is a Pal, minCut is 0, d[i]=0;
• else: the current cut num (first cut s[i..j] and then cut the rest
s[j+1…n-1]) is 1+d[j+1], compare it to the exisiting minCut num
d[i], repalce if smaller.
d[0] is the answer.

class Solution {
public:
    int minCut(string s) {
        int n = s.length();
        if(n == 0) return 0;
        vector<vector<bool>>v(n, vector<bool>(n, false));
        vector<int>dp(n);
        for(int i = n - 1; i >= 0; -- i){
            dp[i] = n - i - 1;
            for(int j = i; j < n; ++ j){
                if(s[i] == s[j] && (j - i < 2 || v[i + 1][j - 1] == true)){
                    v[i][j] = true;
                    if(j == n - 1)
                        dp[i] = 0;
                    else if(dp[j + 1] + 1 < dp[i])
                        dp[i] = dp[j + 1] + 1;
                }
            }
        }
        return dp[0];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值