<p>Given a string <code>s</code>, return <code>true</code> <em>if it is possible to split the string</em> <code>s</code> <em>into three <strong>non-empty</strong> palindromic substrings. Otherwise, return </em><code>false</code>.​​​​​</p>

<p>A string is said to be palindrome if it the same string when reversed.</p>

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

<pre>
<strong>Input:</strong> s = &quot;abcbdd&quot;
<strong>Output:</strong> true
<strong>Explanation: </strong>&quot;abcbdd&quot; = &quot;a&quot; + &quot;bcb&quot; + &quot;dd&quot;, and all three substrings are palindromes.
</pre>

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

<pre>
<strong>Input:</strong> s = &quot;bcbddxy&quot;
<strong>Output:</strong> false
<strong>Explanation: </strong>s cannot be split into 3 palindromes.
</pre>

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

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

class Solution {
public:
    bool isPalindrome(string& s, int l, int r) {
        while (l < r) {
            if (s[l] != s[r]) return false;
            l++;
            r--;
        }
        return true;
    }
    
    int canSplitPalindrome(vector<vector<int>>& dp, string& s, vector<vector<int>>& pal_starts, int cur_idx, int palindrome_cnt) {
        if (cur_idx >= s.size() && palindrome_cnt == 0) return true;
        if (palindrome_cnt <= 0 || cur_idx >= s.size()) return false;

        if (dp[cur_idx][palindrome_cnt] != -1) 
            return dp[cur_idx][palindrome_cnt];

        for (int i = 0; i < pal_starts[cur_idx].size(); ++i) {
            if (canSplitPalindrome(dp, s, pal_starts, pal_starts[cur_idx][i]+1, palindrome_cnt - 1)) {
                dp[cur_idx][palindrome_cnt] = 1;
                return 1;
            }
        }
        dp[cur_idx][palindrome_cnt] = 0;
        return false;
    }
    
    bool checkPartitioning(string s) {
         int n = s.size();
         vector<vector<int>> pal_starts(n);
         vector<vector<int>> dp(n, vector<int>(4, -1));

        // Can be optimized using dp.
         for (int i = n - 1; i >= 0; --i) {
            for (int j = i; j < n; ++j) {
                if (isPalindrome(s, i, j)) {
                    pal_starts[i].push_back(j);
                }
            }
         }

        return canSplitPalindrome(dp, s, pal_starts, 0, 3);
    }
};
52556