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.
懂了,又没完全懂
假设 dp(s)是打印 s 的最小次数
假设 s = “abcabc”
dp("abcabc") = min(
dp("a") + dp("bcabc"),
dp("ab") + dp("cabc"),
dp("abc") + dp("abc") - 1,
dp("abca") + dp("bc"),
dp("abcab") + dp("c")
)
重点在那个dp("abc") + dp("abc") - 1, dp(“abc”) = 3, 所以如果将"abcabc"拆分成 2 组"abc"进行打印,那应该打 6 遍, 但是因为两组的末尾都是"c", 所以我们可以用另一种打印的方法:
第 1 次: “cccccc”
第 2 次: “abcccc”
第 3 次: “accacc”
第 4 次: “abcacc”
第 5 次: “abcabc”
只打印了 5 次
总结一下就是:
dp[i][j]为 s[i…=j]的最小打印次数, i <= k < j, dp[i][j] = min(dp[i][k] + dp[k+1][j] - s[k] == s[j] ? 1 : 0)
use std::collections::HashMap;
impl Solution {
fn dp(chars: &[char], i: usize, j: usize, cache: &mut HashMap<(usize, usize), i32>) -> i32 {
if i == j {
return 1;
}
if let Some(c) = cache.get(&(i, j)) {
return *c;
}
let mut ans = i32::MAX;
for k in i..j {
let left = Solution::dp(chars, i, k, cache);
let right = Solution::dp(chars, k + 1, j, cache);
let sum = if chars[k] == chars[j] {
left + right - 1
} else {
left + right
};
ans = ans.min(sum);
}
cache.insert((i, j), ans);
ans
}
pub fn strange_printer(s: String) -> i32 {
let chars: Vec<char> = s.chars().collect();
Solution::dp(&chars, 0, chars.len() - 1, &mut HashMap::new())
}
}

文章描述了一个特殊的打印机,它每次只能打印相同字符的序列。给定一个字符串,目标是确定打印机打印该字符串所需的最小次数。通过递归和动态规划方法,计算每个子串的最小打印次数,并考虑重叠部分的优化。示例展示了如何分析和计算字符串abcabc的最小打印次数。
1019

被折叠的 条评论
为什么被折叠?



