LeetCode每日一题(664. Strange Printer)

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())
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值