<p>Given a string <code>s</code>, find <em>the longest palindromic <strong>subsequence</strong>&#39;s length in</em> <code>s</code>.</p>

<p>A <strong>subsequence</strong> is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements.</p>

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

<pre>
<strong>Input:</strong> s = &quot;bbbab&quot;
<strong>Output:</strong> 4
<strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bbbb&quot;.
</pre>

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

<pre>
<strong>Input:</strong> s = &quot;cbbd&quot;
<strong>Output:</strong> 2
<strong>Explanation:</strong> One possible longest palindromic subsequence is &quot;bb&quot;.
</pre>

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

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

class Solution:
    def longestPalindromeSubseq(self, s: str) -> int:
        @cache
        def longest_palindromic_subsequence(start: int, end: int) -> int:
            if end - start <= 1:
                return end - start
            
            if s[start] == s[end - 1]:
                return 2 + longest_palindromic_subsequence(start + 1, end - 1)
            
            return max(
                longest_palindromic_subsequence(start + x, end + y)
                for x, y in (
                    (1, 0),
                    (0, -1),
                    (1, -1)
                )
            )
        
        return longest_palindromic_subsequence(0, len(s))
        #   b   b   b   a   b
        # f(i, j) = longest palindromic subsequence in s[i:j].
        # F(s) = f(0, len(s)).
        # Base cases:
        # f(i, i) = 0
        # f(i, i + 1) = 1
        # Recurrence:
        # If s[i] == s[j - 1]:
        #   f(i, j) = 2 + f(i + 1, j - 1)
        # Else:
        #   f(i, j) = max(f(i + x, j + y) for x, y in ((1, 0), (0, -1), (1, -1))).
        # This problem is very similar to edit distance.
        # Time:
        # - Total subproblems: O(n**2)
        # - work per subproblem: O(1)
        # - O(N^2) total.
        # Space:
        # - O(N^2).
99918