leetcode 664. Strange Printer
Posted いいえ敗者
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode 664. Strange Printer相关的知识,希望对你有一定的参考价值。
There is a strange printer with the following two special requirements:
- 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 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]; } };
以上是关于leetcode 664. Strange Printer的主要内容,如果未能解决你的问题,请参考以下文章
[LeetCode] Strange Printer 奇怪的打印机
LeetCode 664 奇怪的打印机[动态规划] HERODING的LeetCode之路
LeetCode664. 奇怪的打印机 / 剑指 Offer 55 - I. 二叉树的深度 / 剑指 Offer 55 - II. 平衡二叉树