【LeetCode 1278】 Palindrome Partitioning III

题目描述

You are given a string s containing lowercase letters and an integer k. You need to :

First, change some characters of s to other lowercase English letters.
Then divide s into k non-empty disjoint substrings such that each substring is palindrome.
Return the minimal number of characters that you need to change to divide the string.

Example 1:

Input: s = "abc", k = 2
Output: 1
Explanation: You can split the string into "ab" and "c", and change 1 character in "ab" to make it palindrome.

Example 2:

Input: s = "aabbc", k = 3
Output: 0
Explanation: You can split the string into "aa", "bb" and "c", all of them are palindrome.

Example 3:

Input: s = "leetcode", k = 8
Output: 0

Constraints:

1 <= k <= s.length <= 100.
s only contains lowercase English letters.

思路

动态规划。dp[i][k]表示0~i的字符串,划分为k段的最小代价。遍历j∈[0,i),为k-1可能的划分位置,寻找最小的位置。

代码

class Solution {
public:
    int palindromePartition(string s, int k) {
        int n = s.length();
        vector<vector<int> > cost(n, vector<int>(n, 0));
        for (int l=2; l<=n; ++l) {
            for (int i=0, j=i+l-1; j<n; ++i, ++j) {
                cost[i][j] = (s[i] != s[j]) + cost[i+1][j-1];
            }
        }
        
        vector<vector<int> > dp(n, vector<int>(k+1, INT_MAX/2));
      
        for (int i=0; i<n; ++i) {
            dp[i][1] = cost[0][i];
            for (int kk=2; kk<=k; ++kk) {
                for (int j=0; j<i; ++j) {
                    dp[i][kk] = min(dp[i][kk], dp[j][kk-1]+cost[j+1][i]);
                }
            }
        }
        
        return dp[n-1][k];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值