664Strange Printer

16 篇文章 0 订阅
3 篇文章 0 订阅

题目描述:
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;

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值