leetcode 664. Strange Printer 奇怪的打印机 + 动态规划DP
来源:互联网 发布:ipa版本淘宝的微淘 编辑:程序博客网 时间:2024/05/29 15:50
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.
对于每个string,考虑最后XXXXX,分成2部分。如果第一部分的最后与第二部分的最后一样(为什么考虑最后一位呢?就是为什么是j-1和i+d呢?因为我们现在求得是i-i+d范围,要么是后半部分开始的j,要么是i+d,试想如果j和j+1是一样的,那么就会在j的下一个循环被考虑到,因此我们只需要考虑后半部分的结尾就可以,当然为了以防万一也可以吧j和j+1相等的情况也写进代码) 那在print第一部分的最后的时候就可以吧第二部分的最后也顺带处理掉了,这时候就要减一 , 如果不能分成2部分,比如aaaaaa,在减一的时候就处理掉了
参考链接 664. Strange Printer
代码如下:
#include <iostream>#include <vector>#include <map>#include <set>#include <queue>#include <stack>#include <string>#include <climits>#include <algorithm>#include <sstream>#include <functional>#include <bitset>#include <numeric>#include <cmath>#include <regex>using namespace std;class Solution {public: int strangePrinter(string s) { int n = s.length(); if (n == 0) return 0; vector<vector<int>> dp(n, vector<int>(n, 0)); for (int i = 0; i < n; i++) dp[i][i] = 1; for (int len = 1; len <= n; len++) { for (int i = 0; i + len < n; i++) { dp[i][i + len] = len + 1; for (int j = i + 1; j <= i + len; j++) { int t = dp[i][j - 1] + dp[j][i + len]; if (s[j - 1] == s[i + len]) t--; dp[i][i + len] = min(dp[i][i + len], t); } } } return dp[0][n - 1]; }};
- leetcode 664. Strange Printer 奇怪的打印机 + 动态规划DP
- [leetcode]664. Strange Printer
- [Leetcode]664. Strange Printer
- Leetcode: 664. Strange Printer
- Strange Printer (leetcode)
- 算法练习(7) —— 动态规划 Strange Printer
- 664. Strange Printer
- 664. Strange Printer
- 【LeetCode】664.Strange Printer(hard)解题报告
- LeetCode: -Dynamic Programming-Strange Printer[664]
- Strange Printer
- [Printer]Zebra条码打印机的使用
- Leetcode 动态规划DP类题目
- leetcode 62. Unique Paths DP动态规划
- 664Strange Printer
- 一、动态规划(2)奇怪的电梯
- PDFMaker无法找到Adobe PDF Printer的打印机驱动
- 佳博打印机GP-Printer TEXT 命令无效的问题
- 122. Best Time to Buy and Sell Stock II
- java 接口调用memcached
- 单选框radio和复选框checkbox文字垂直居中问题
- SqueezeNet的Caffe实现
- python中的装饰器,函数带参数的装饰器,带类参数的装饰器
- leetcode 664. Strange Printer 奇怪的打印机 + 动态规划DP
- 如何用Python智能批量压缩图片?
- java注解开发
- YUV 转RGB公式说明
- jmeter中用同一个正则表达式获取多个响应返回值
- js代码规范
- java : java -jar,java -cp,jar cvf 命令详解
- 201709-2 公共钥匙盒 解题报告
- 搭建Sphinx全文搜索引擎