【LeetCode】664.Strange Printer(hard)解题报告

本文介绍了解决LeetCode上Strange Printer问题的一种动态规划方法。该问题要求找出打印给定字符串所需的最少轮数,打印机只能逐个字符打印相同字符,并且可以覆盖原有字符。通过构建二维DP表格并利用子问题最优性来降低时间复杂度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【LeetCode】664.Strange Printer(hard)解题报告

tags: DP

题目地址:https://leetcode.com/problems/strange-printer/description/
题目描述:

  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.

Example1:

Input: "aaabbb"
Output: 2
Explanation: Print "aaa" first and then print "bbb".

Example2:

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'.

分析:

s:       abc......d
index:   i    k   j
f(i,j): min steps to print s
f(i,j): worse case j-i+1
f(i,j): min(f(i,k) + f(k+1,j) - 1 if(s[k] == s[j] {i <= k < j}))
aba

Solutions:

class Solution {
    public int strangePrinter(String s) {
        if(s.length()==0){
            return 0;
        }
        int len = s.length();
        int[][] dp = new int[len][len];
        for(int i=0 ; i<len ; i++){
            dp[i][i] = 1 ;
        }
        for(int j=1 ; j<len ; j++){
            for(int i=0 ; i+j<len ; i++){
                dp[i][i+j] = j+1 ;
                for(int k=i ; k<i+j ; k++){
                    int total = dp[i][k] + dp[k+1][i+j];
                    if(s.charAt(k) == s.charAt(i+j)){
                        total--;
                    }
                    dp[i][i+j] = Math.min(dp[i][i+j],total);
                }
            }
        }
        return dp[0][len-1];
    }
}

Date:2017年11月5日

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值