【LeetCode 664】 Strange Printer

题目描述

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:

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]表示从i到j的字符串打印次数。
遍历长度,遍历字符串,每次从 i 到 j 字符串中,遍历和s[i]相等的字符k,此时可以划分为[i+1][k-1]和[k][j]两个子问题。

代码

class Solution {
public:
    int strangePrinter(string s) {
        if (s.empty()) return 0;
        int n = s.length();
        vector<vector<int> > dp(n, vector<int>(n, 0));
        
        for (int l=1; l<=n; ++l) {
            for (int i=0,j=i+l-1; j<n; ++i, ++j) {
                dp[i][j] = (i == j? 1 : dp[i+1][j] + 1);
                for (int k=i+1; k<=j; ++k) {
                    if (s[i] == s[k]) {
                        dp[i][j] = min(dp[i][j], dp[i+1][k-1]+dp[k][j]);
                    }
                }
            }
        }
                            
        return dp[0][n-1];
    }
};
发布了243 篇原创文章 · 获赞 10 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/iCode_girl/article/details/104420742