<p>Given a string <code>s</code> containing only three types of characters: <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code> and <code>&#39;*&#39;</code>, return <code>true</code> <em>if</em> <code>s</code> <em>is <strong>valid</strong></em>.</p>

<p>The following rules define a <strong>valid</strong> string:</p>

<ul>
	<li>Any left parenthesis <code>&#39;(&#39;</code> must have a corresponding right parenthesis <code>&#39;)&#39;</code>.</li>
	<li>Any right parenthesis <code>&#39;)&#39;</code> must have a corresponding left parenthesis <code>&#39;(&#39;</code>.</li>
	<li>Left parenthesis <code>&#39;(&#39;</code> must go before the corresponding right parenthesis <code>&#39;)&#39;</code>.</li>
	<li><code>&#39;*&#39;</code> could be treated as a single right parenthesis <code>&#39;)&#39;</code> or a single left parenthesis <code>&#39;(&#39;</code> or an empty string <code>&quot;&quot;</code>.</li>
</ul>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<pre><strong>Input:</strong> s = "()"
<strong>Output:</strong> true
</pre><p><strong class="example">Example 2:</strong></p>
<pre><strong>Input:</strong> s = "(*)"
<strong>Output:</strong> true
</pre><p><strong class="example">Example 3:</strong></p>
<pre><strong>Input:</strong> s = "(*))"
<strong>Output:</strong> true
</pre>
<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= s.length &lt;= 100</code></li>
	<li><code>s[i]</code> is <code>&#39;(&#39;</code>, <code>&#39;)&#39;</code> or <code>&#39;*&#39;</code>.</li>
</ul>

class Solution {
private:
    bool rec(string s, int i, int x, vector<vector<int>> &dp, int n) {
        // Base case: if we've processed the entire string, check if balance `x` is zero
        if (i == s.length()) {
            return x == 0;
        }
        
        // If x is negative, too many closing parentheses, so invalid
        if (x < 0) return false;
        
        // Check if already calculated
        if (dp[i][x] != -2) return dp[i][x];
        
        bool ans = false;
        
        // Recurse based on the current character in the string
        if (s[i] == '(') {
            ans = rec(s, i + 1, x + 1, dp, n);
        } 
        else if (s[i] == ')') {
            ans = rec(s, i + 1, x - 1, dp, n);
        } 
        else if (s[i] == '*') {
            // '*' can be treated as an empty string, '(', or ')'
            ans = rec(s, i + 1, x, dp, n) || rec(s, i + 1, x + 1, dp, n) || rec(s, i + 1, x - 1, dp, n);
        }

        // Memoize the result
        return dp[i][x] = ans;
    }
    
public:
    bool checkValidString(string s) {
        int n = s.length();
        
        // DP table to memoize results, with size sufficient for balance range
        // Shifting x by n to handle negative values of x
        vector<vector<int>> dp(n + 1, vector<int>(2 * n + 1, -2));
        
        // Start the recursion with x shifted by n (initial balance of 0 shifted to n)
        return rec(s, 0, 0, dp, n);
    }
};
28060