[LeetCode]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.

动态规划。

设f(n)表示s的前n个字符组成的子串最少被切分为回文子串的数目,那么

f(n) = min{f(k) + 1, s[k .. n]是回文,其中0 < k <=n}

这个过程需要多次判断s[k .. n]是否是回文,我么可以使用备忘录的方法将s[k..n]是否是回文记录下来,以避免重复判断。

p(i, j) = p(i + 1, j - 1), 如果s[i] = s[j]; 否则p(i, j) = false

class Solution {
public:
    bool isPalindrome(string &s, vector<vector<int>> &r, int i, int j) {
        int &ans = r[i][j];
        if (ans < 0) {
            if (i >= j) ans = 1;
            else if (s[i] != s[j]) ans = 0;
            else ans = isPalindrome(s, r, i + 1, j - 1);
        }
        return ans == 1;
    }
    
    int minCut(string s) {
        int n = s.length();
        if (0 == n) return 0;
        vector<vector<int>> r(n, vector<int>(n, -1));
        // dp[i] is the minimum cuts needed for s[1..i]
        vector<int> dp(n + 1, 0);
        for (int i = 1; i <= n; i++) {
            dp[i] = 1 << 30;
            for (int j = i - 1; j >= 0; j--) {
                if (dp[j] + 1 < dp[i] && isPalindrome(s, r, j, i - 1))
                    dp[i] = dp[j] + 1;
            }
        }
        return dp[n] - 1;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值