664. Strange Printer
LeetCode 664. Strange Printer
Description
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:
Example 2:
Hint : Length of the given string will not exceed 100.
Tags
Dynamic Programming, Depth-first Search
Solution
State:
f[i][j]
represents the minimum operations to prints[i:j]
;Transform:
s[i]=s[j]
: We only need to consider the minimum operations to prints[i:j-1]
, because we can prints[i]
ands[j]
in one single operation;s[i]≠s[j]
: We have to splits[i:j]
into 2 parts and find the minimum operations required by both parts.
Edge cases:
f[i][i]=1
, which means we only need to print once for a single character;Answer:
f[0][n - 1]
.
Note that we iterate i
from right to left and j
from left to right, to ensure we have obtained f[i][k]
and f[k+1][j]
when we need to compute f[i][j]
.
Complexity
Time complexity:
Space complexity:
Code
Reference
Last updated
Was this helpful?