<p>Given a string <code>s</code>, partition <code>s</code> such that every <span data-keyword="substring-nonempty">substring</span> of the partition is a <span data-keyword="palindrome-string">palindrome</span>.</p>

<p>Return <em>the <strong>minimum</strong> cuts needed for a palindrome partitioning of</em> <code>s</code>.</p>

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

<pre>
<strong>Input:</strong> s = &quot;aab&quot;
<strong>Output:</strong> 1
<strong>Explanation:</strong> The palindrome partitioning [&quot;aa&quot;,&quot;b&quot;] could be produced using 1 cut.
</pre>

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

<pre>
<strong>Input:</strong> s = &quot;a&quot;
<strong>Output:</strong> 0
</pre>

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

<pre>
<strong>Input:</strong> s = &quot;ab&quot;
<strong>Output:</strong> 1
</pre>

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

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

class Solution:
    def minCut(self, s: str) -> int:
        endPoints = defaultdict(set)
        n = len(s)
        palindrome = []
        for i in range(n):
            palindrome.append([None] * n)

        @cache
        def isPalindrome(left, right):
            if palindrome[left][right] is not None:
                return palindrome[left][right]
            if left == right:
                endPoints[left].add(right)
                palindrome[left][right] = True
                return True
            elif left + 1 == right:
                if s[left] == s[right]:
                    endPoints[left].add(right)
                palindrome[left][right] = s[left] == s[right]
                return s[left] == s[right]
            
            ret = s[left] == s[right] and isPalindrome(left + 1, right - 1)
            if ret:
                endPoints[left].add(right)
            palindrome[left][right] = ret
            return ret

        for left in range(n):
            for right in range(left, n):
                isPalindrome(left, right)

        # print(endPoints)
        queue = deque([(0, 0)])
        visited = set([0])

        while queue:
            cuts, pos = queue.popleft()
            # if pos == n - 1:
            #     return cuts

            for end in endPoints[pos]:
                if end + 1 in visited:
                    continue

                visited.add(end+1)
                queue.append((cuts + 1, end + 1))

                if end + 1 == n:
                    return cuts

        return 0

435960