<p>There is a strange printer with the following two special properties:</p>

<ul>
	<li>The printer can only print a sequence of <strong>the same character</strong> each time.</li>
	<li>At each turn, the printer can print new characters starting from and ending at any place and will cover the original existing characters.</li>
</ul>

<p>Given a string <code>s</code>, return <em>the minimum number of turns the printer needed to print it</em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;aaabbb&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print &quot;aaa&quot; first and then print &quot;bbb&quot;.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> s = &quot;aba&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong> Print &quot;aaa&quot; first and then print &quot;b&quot; from the second place of the string, which will cover the existing character &#39;a&#39;.
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 100</code></li>
	<li><code>s</code> consists of lowercase English letters.</li>
</ul>

class Solution {
public:
    using Memo = unordered_map<int, unordered_map<int, int>>;

    int strangePrinter(string s) {
        Memo memo;
        return dfs(memo, s, 0, s.size());
    }

    int dfs(Memo &memo, const string &s, int i, int j) {
        if (i == j) return 0;
        if (i + 1 == j) return 1;
        if (memo[i].count(j)) return memo[i][j];

        int ret = min(dfs(memo, s, i + 1, j), dfs(memo, s, i, j - 1)) + 1;

        if (s[i] == s[i + 1]) {
            ret = min(ret, dfs(memo, s, i + 1, j));
        }

        if (s[j - 2] == s[j - 1]) {
            ret = min(ret, dfs(memo, s, i, j - 1));
        }

        if (s[i] == s[j - 1]) {
            if (j - i > 2 && (s[i] == s[i + 1] || s[j - 2] == s[j - 1])) {
                ret = min(ret, dfs(memo, s, i + 1, j - 1));
            } else {
                ret = min(ret, dfs(memo, s, i + 1, j - 1) + 1);
            }
        }

        for (int k = i + 1; k < j; ++k) {
            if (s[i] == s[j - 1]) {
                ret = min(ret, dfs(memo, s, i, k) + dfs(memo, s, k, j) - 1);
            } else {
                ret = min(ret, dfs(memo, s, i, k) + dfs(memo, s, k, j));
            }
        }

        return memo[i][j] = ret;
    }
};
29327