LeetCode664. Strange Printer——区间dp

文章讨论了一种特殊的打印机,只能连续打印相同字符,要求找出打印给定字符串所需的最少步骤。通过动态规划方法求解,计算覆盖整个字符串的最小操作次数。

一、题目

There is a strange printer with the following two special properties:

The printer can only print a sequence of the same character each time.
At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.
Given a string s, return the minimum number of turns the printer needed to print it.

Example 1:

Input: s = “aaabbb”
Output: 2
Explanation: Print “aaa” first and then print “bbb”.
Example 2:

Input: s = “aba”
Output: 2
Explanation: Print “aaa” first and then print “b” from the second place of the string, which will cover the existing character ‘a’.

Constraints:

1 <= s.length <= 100
s consists of lowercase English letters.

二、题解

class Solution {
public:
    int strangePrinter(string s) {
        int n = s.size();
        vector<vector<int>> dp(n,vector<int>(n,0));
        dp[n-1][n-1] = 1;
        for(int i = 0;i < n - 1;i++){
            dp[i][i] = 1;
			dp[i][i + 1] = s[i] == s[i + 1] ? 1 : 2;
        }
        for (int l = n - 3; l >= 0; l--) {
			for (int r = l + 2; r < n; r++) {
				if (s[l] == s[r]) {
					dp[l][r] = dp[l][r - 1];
				} else {
					int res = INT_MAX;
					for (int m = l; m < r; m++) {
						res = min(res, dp[l][m] + dp[m + 1][r]);
					}
					dp[l][r] = res;
				}
			}
		}
		return dp[0][n - 1];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值