<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 {
private:
    string s;
    vector<vector<vector<int>>> cache; // cache[start][length - 1][letter]

public:
    int strangePrinter(string s) {
        this->s = s;
        cache.assign(s.length(), vector<vector<int>>());

        for (int i = 0; i < s.length(); i++) {
            cache[i].assign(s.length() - i, vector<int>(26, -1));
        }

        return 1 + min(
            getTurns(0, s.length(), s[0]),
            getTurns(0, s.length(), s.back())
        );
    }

private:
    int getTurns(int start, int length, char letter) {
        if (length <= 0) {
            return 0;
        } else {
            int& result = cache[start][length - 1][letter - 'a'];

            if (result < 0) {
                char firstLetter = s[start];
                char lastLetter = s[start + length - 1];

                if (firstLetter == letter) {
                    result = getTurns(start + 1, length - 1, letter);
                } else if (lastLetter == letter) {
                    result = getTurns(start, length - 1, letter);
                } else {
                    result = 1 + (firstLetter == lastLetter
                        ? getTurns(start + 1, length - 2, firstLetter)
                        : min(
                            getTurns(start + 1, length - 1, firstLetter),
                            getTurns(start, length - 1, lastLetter)
                        )
                    );

                    for (int firstLength = 1; firstLength < length; firstLength++) {
                        result = min(result, getTurns(start, firstLength, letter) + getTurns(start + firstLength, length - firstLength, letter));
                    }
                }
            }

            return result;
        }
    }
};

61547