664Strange Printer
来源:互联网 发布:ios开发数据存储 编辑:程序博客网 时间:2024/06/05 07:18
题目描述:
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[i][j]表示打印下标[i .. j]的子串所需的最少打印次数;记目标串为s
状态转移方程为:
dp[y][x] = min(dp[y][x], dp[y][z-1] + dp[z][x-1] + k) 当s[x-1] != s[z-1]时k取值1,否则k取值0
#include<bits/stdc++.h>using namespace std;//dfs版本//int dp[110][110];//string ss;//int dfs(int l,int r)//{// // cout<<l<<' '<<r<<endl;// if(dp[l][r]!=-1) return dp[l][r];// if(l==r) {dp[l][r]=1;return 1;}// else {// for(int i=l;i<r;i++)// {// int z=dfs(l,i)+dfs(i+1,r);// if(ss[l]==ss[i+1]) z--;// if(dp[l][r]==-1||z<dp[l][r])// {// dp[l][r]=z;// }// }// // cout<<l<<' '<<r<<endl;// // cout<<"dp="<<dp[l][r]<<endl;// return dp[l][r];// }//}////class Solution {//public:// int strangePrinter(string s) {// ss=s;// memset(dp,-1,sizeof(dp));//// return dfs(0,s.size()-1);// }//};//递推版本class Solution {public: int strangePrinter(string s) { int len=s.size(); int dp[110][110]; for(int i=0;i<110;i++) for(int j=0;j<110;j++) dp[i][j]=0x7ffffff; for(int i=0;i<len;i++) { for(int j=0;j+i<len;j++) { if(i==0) {dp[j][j]=1;continue;} for(int z=j;z<j+i;z++) { dp[j][j+i]=min(dp[j][j+i],dp[j][z]+dp[z+1][j+i]+(s[j]==s[z+1]?-1:0)); } } } return dp[0][len-1]; }};int main(){ Solution sol; string s("aaabbb"); cout<<sol.strangePrinter(s)<<endl;}
- 664Strange Printer
- Strange Printer
- LeetCode: -Dynamic Programming-Strange Printer[664]
- 664. Strange Printer
- Strange Printer (leetcode)
- [leetcode]664. Strange Printer
- 664. Strange Printer
- [Leetcode]664. Strange Printer
- Leetcode: 664. Strange Printer
- leetcode_664. Strange Printer ? 待解决
- 算法练习(7) —— 动态规划 Strange Printer
- 【LeetCode】664.Strange Printer(hard)解题报告
- leetcode 664. Strange Printer 奇怪的打印机 + 动态规划DP
- Printer
- Printer Printer
- Printer.cs
- printer repair
- linux printer
- PAT--1025. PAT Ranking
- 动态数组链表
- 初识java
- 浅谈web语义化
- Caffe框架初步理解
- 664Strange Printer
- HDU 5869 Different GCD Subarray Query (离线处理 树状数组)
- 前端性能优化
- linux高级编程
- windows下搭建Ruby+Sass环境
- AndroidStudio模板简介
- 向量化编程
- 24. flock() 函数
- Unity_固定分辨率运行游戏_082