<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>

// <editor-fold defaultstate="collapsed" desc="#define OUT(...)">
#ifndef OUT
#define OUT(...)
#endif
// </editor-fold>

template<class Cache>
int dfs(int left, int right, int color, const string &s, const vector<vector<int> > &vv, Cache &&cache) {
    while (left <= right && s[left] == color + 'a') ++left;
    while (left <= right && s[right] == color + 'a') --right;

    if (left > right) return 0;
    if (left == right) return 1;

    int &tmp = cache[color][left][right];
    if (tmp >= 0) return tmp;

    int ans = 1 + min(
            dfs(left + 1, right, color, s, vv, cache),
            dfs(left, right - 1, color, s, vv, cache));
    {
        int c = s[left] - 'a';
        auto &&v = vv[c];
        auto p = upper_bound(v.begin(), v.end(), left), e = v.end();
        for (; p != e && *p <= right; ++p) {
            ans = min(ans, 1 + dfs(left, *p, c, s, vv, cache)
                     + dfs(*p + 1, right, color, s, vv, cache));
        }
    }
    return tmp = ans;
}

class Solution {
public:
    static int strangePrinter(string &&s) {
        return strangePrinter(s);
    }

    static int strangePrinter(string &s) {
        s.erase(unique(s.begin(), s.end()), s.end());
        OUT(s);
        vector<vector<int> > v(26);

        const int len = (int) s.length();
        for (int i = 0; i < len; ++i) v[s[i] - 'a'].push_back(i);

        vector<vector<vector<int> > > dp(27, vector<vector<int> >(len, vector<int>(len, -1)));

        return dfs(0, len - 1, 26, s, v, dp);
    }

};

74077