zoukankan      html  css  js  c++  java
  • 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];
        }
    };
  • 相关阅读:
    vue 路由嵌套 (子路由跳转报错或者失效解决方法)
    vue-cli3主题色系统
    vue项目哀悼日
    el-upload 文件上传显示进度
    课表
    uni-app 开发钉钉小程序
    Linux/Centos/Ubuntu crontab备份数据库
    【转】鲁迅为厦大题写校名,为啥4个字错了3个?专家:鲁迅故意写错的。
    计数单位资料汇总(个十百千兆京...,分厘毫丝忽微纤沙尘埃...)
    【转】如意算盘:中国的第五大发明
  • 原文地址:https://www.cnblogs.com/pk28/p/7466550.html
Copyright © 2011-2022 走看看