Strange Printer_Week14

Strange Printer_Week14

题目:(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’.

难度: Hard

解题思路:
这道题跟之前做过的只能复制粘贴一段的题有点像,但又不完全一样。因为可以覆盖,所以不用拆成一截截来做。
思路是用学过的动态规划来解决,把字符串从长度为0到长度为size的最短路径算出来,用转移方程来判断最终结果。

为了简单好理解,所以使用了递归的方法来实现,代码如下:

class Solution {
public:
    int strangePrinter(std::string s)
    {
        memset(f, 0, sizeof(f));
        int len = (int)s.size();
        return dfs(s, 0, len - 1);
    }

private:
    /*数组用于存储动态规划状态,f[i][j]等于打印字符串第i个字符到第j个字符所需的最短路径*/
    int f[100][100];


    int dfs(const std::string& s, int l, int r)
    {
        if (l > r) {
            return 0;
        }
        if (f[l][r]) {
            return f[l][r];
        }
        //默认转移方程为前一个状态的字符串加上一个新字符+1的状态
        f[l][r] = dfs(s, l, r - 1) + 1;

        for (int i = l; i < r; ++i)
        {
            if (s[i] == s[r])
            {
            //转移方程判断当前一个状态+1,和拆成两段字符串加在一起的步数,哪个更短就取哪一个
                f[l][r] = min(f[l][r], dfs(s, l, i) + dfs(s, i + 1, r - 1));
            }
        }
        return f[l][r];
    }

};

猜你喜欢

转载自blog.csdn.net/m0_38072045/article/details/78819232