1. 程式人生 > >【LeetCode】664.Strange Printer(hard)解題報告

【LeetCode】664.Strange Printer(hard)解題報告

【LeetCode】664.Strange Printer(hard)解題報告

tags: DP

  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日