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];
        }
    };
  • 相关阅读:
    【玩转开源】制作Docker镜像
    【玩转开源】Linux C 检测网口热插拔
    【玩转开源】BananaPi R2 —— 第四篇 Openwrt Luci 初探
    【玩转开源】BananaPi R2 —— 第二篇 Openwrt 网口配置分析
    .NET Core 中AutoMapper使用配置
    ElementUI 中控件 Select 大数据量渲染处理
    Echart处理X轴显示不全问题
    C#WebAPI中中log4net的配置步骤
    iis7.5 部署WebAPI
    core2.2部署IIS
  • 原文地址:https://www.cnblogs.com/pk28/p/7466550.html
Copyright © 2011-2022 走看看