一、题目
There is a strange printer with the following two special properties:
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 place and will cover the original existing characters.
Given a string s, return the minimum number of turns the printer needed to print it.
Example 1:
Input: s = “aaabbb”
Output: 2
Explanation: Print “aaa” first and then print “bbb”.
Example 2:
Input: s = “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’.
Constraints:
1 <= s.length <= 100
s consists of lowercase English letters.
二、题解
class Solution {
public:
int strangePrinter(string s) {
int n = s.size();
vector<vector<int>> dp(n,vector<int>(n,0));
dp[n-1][n-1] = 1;
for(int i = 0;i < n - 1;i++){
dp[i][i] = 1;
dp[i][i + 1] = s[i] == s[i + 1] ? 1 : 2;
}
for (int l = n - 3; l >= 0; l--) {
for (int r = l + 2; r < n; r++) {
if (s[l] == s[r]) {
dp[l][r] = dp[l][r - 1];
} else {
int res = INT_MAX;
for (int m = l; m < r; m++) {
res = min(res, dp[l][m] + dp[m + 1][r]);
}
dp[l][r] = res;
}
}
}
return dp[0][n - 1];
}
};