# 664. Strange Printer

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.

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[i][j] = min(dp[i][j], dp[i + 1][k - 1] + dp[k][j]       (s[k] == s[i] and i + 1 <= k <= j)
``````

``````class Solution {
public:
int strangePrinter(string s) {
int n = s.size();
vector<vector<int>> dp(n, vector<int>(n, 0));
for (int i = n - 1; i >= 0; --i) {
for (int j = i; j < n; ++j) {
dp[i][j] = (i == j) ? 1 : (1 + dp[i + 1][j]);
for (int k = i + 1; k <= j; ++k) {
if (s[k] == s[i]) dp[i][j] = min(dp[i][j], dp[i + 1][k - 1] + dp[k][j]);
}
}
}
return (n == 0) ? 0 : dp[0][n - 1];
}
};
``````

``````class Solution {
public:
int strangePrinter(string s) {
int n = s.size();
vector<vector<int>> memo(n, vector<int>(n, 0));
return helper(s, 0, n - 1, memo);
}
int helper(string s, int i, int j, vector<vector<int>>& memo) {
if (i > j) return 0;
if (memo[i][j]) return memo[i][j];
memo[i][j] = helper(s, i + 1, j, memo) + 1;
for (int k = i + 1; k <= j; ++k) {
if (s[k] == s[i]) {
memo[i][j] = min(memo[i][j], helper(s, i + 1, k - 1, memo) + helper(s, k, j, memo));
}
}
return memo[i][j];
}
};
``````

Remove Boxes

Burst Balloons

Zuma Game

https://discuss.leetcode.com/topic/100137/java-solution-dp

https://discuss.leetcode.com/topic/100212/c-29ms-dp-solution

https://discuss.leetcode.com/topic/100135/java-o-n-3-short-dp-solution

LeetCode All in One 题目讲解汇总(持续更新中…)

 微信打赏 Venmo 打赏
（欢迎加入博主的知识星球，博主将及时答疑解惑，并分享刷题经验与总结，试运营期间前五十位可享受半价优惠～）

×

Help us with donation