• leetcode 664. Strange Printer


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

    1. The printer can only print a sequence of the same character each time.
    2. At each turn, the printer can print new characters starting from and ending at any places, and will cover the original existing characters.

    Given a string consists of lower English letters only, your job is to count the minimum number of turns the printer needed in order to print it.

    Example 1:

    Input: "aaabbb"
    Output: 2
    Explanation: Print "aaa" first and then print "bbb".
    

    Example 2:

    Input: "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'.
    

    Hint: Length of the given string will not exceed 100.

    思路:
    区间dp
    区间dp顾名思义就是 区间上的dp,也就是从小到大枚举区间,每个区间就是一个最优子结构,由小到大地推得到最后的期间【0,n-1】

    本题可以需要注意,如果两个区间a和b 如果a的开始和b的开始位置字符相同 那么 合并之后 需要的代价为 a+b - 1
    举个例子
    字符串abba 对于[0,2]和[3,3]区间,如果这两个区间合并的话 那么需要代价是2+1 -1. 为什么要减去1呢,题目中已经说了。。。
    代码如下:

    class Solution {
    public:
        int strangePrinter(string s) {
            int dp[110][110];
            int n = s.length();
            if (n == 0) return 0;
            memset(dp, 0x3f3f3f3f, sizeof dp);
            for (int i = 0; i < n; ++i) dp[i][i] = 1;
            for (int p = 1; p < n; ++p) {
                for (int i = 0; i < n - p; ++i) {
                    int j = i + p;
                    for (int k = i; k <= j; ++k) {
                        int w = dp[i][k] + dp[k + 1][j];
                        if (s[i] == s[k + 1]) --w; // 第一段的起点 和第二段的起点一样 执行--
                        dp[i][j] = min(dp[i][j], w);
                    }
                } 
            }
            return dp[0][n - 1];
        }
    };
  • 相关阅读:
    Educational Codeforces Round 6
    Codeforces Round #373 (Div. 2)
    尺取法
    Codeforces Round #542 [Alex Lopashev Thanks-Round] (Div. 2)
    逆元(数论倒数)
    最大公约数gcd,最小公倍数lcm,扩展欧几里得
    hdu 6395 Sequence (分段矩阵快速幂)
    快速幂
    hdu 6432 Cyclic
    hdu 6397 charactor encoding
  • 原文地址:https://www.cnblogs.com/pk28/p/7466550.html
Copyright © 2020-2023  润新知