<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"><strong>palindrome</strong></span>. Return <em>all possible palindrome partitioning of </em><code>s</code>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "aab"
<strong>Output:</strong> [["a","a","b"],["aa","b"]]
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "a"
<strong>Output:</strong> [["a"]]
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 16</code></li>
	<li><code>s</code> contains only lowercase English letters.</li>
</ul>

class Solution {
public:
    vector<vector<string>> pal_parts;
    vector<vector<int>> dp;
    bool is_palindrome(string s, int i, int j){
        if(i == j) dp[i][j] = 1;
        else if(i + 1 == j){
            dp[i][j] = 0;
            if(s[i] == s[j]) dp[i][j] = 1;
        }
        else if(dp[i][j] != -1) return dp[i][j];
        else {
            dp[i][j] = is_palindrome(s, i + 1, j - 1) * (s[i] == s[j]);
        }
        return dp[i][j];
    }    

    void helper(string s, vector<string> &part, string curr, vector<vector<int>> &ind, int i, int j){
        if(j == (int) s.size()){
            bool palindromic = true;
            int m = (int) part.size();
            for(int k = 0; k < m; k++){
                if(!is_palindrome(s, ind[k][0], ind[k][1])){
                    palindromic = false;
                    break;
                }
            }
            if(curr != "") palindromic = false;
            if(palindromic) pal_parts.push_back(part);
            return;
        }

        curr += s[j];
        helper(s, part, curr, ind, i, j + 1);

        part.push_back(curr);
        ind.push_back({i, j});
        helper(s, part, "", ind, j + 1, j + 1);
        
        part.pop_back();
        ind.pop_back();
    }
    vector<vector<string>> partition(string s) {
        int n = (int) s.size();
        dp.resize(n, vector<int> (n, -1));
        vector<vector<int>> ind;
        vector<string> p;
        helper(s, p, "", ind, 0, 0);
        return pal_parts;
    }
};
234909