<p>Alice and Bob take turns playing a game, with Alice starting first.</p>

<p>Initially, there are <code>n</code> stones in a pile. On each player&#39;s turn, that player makes a <em>move</em> consisting of removing <strong>any</strong> non-zero <strong>square number</strong> of stones in the pile.</p>

<p>Also, if a player cannot make a move, he/she loses the game.</p>

<p>Given a positive integer <code>n</code>, return <code>true</code> if and only if Alice wins the game otherwise return <code>false</code>, assuming both players play optimally.</p>

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

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> true
<strong>Explanation: </strong>Alice can remove 1 stone winning the game because Bob doesn&#39;t have any moves.</pre>

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

<pre>
<strong>Input:</strong> n = 2
<strong>Output:</strong> false
<strong>Explanation: </strong>Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -&gt; 1 -&gt; 0).
</pre>

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

<pre>
<strong>Input:</strong> n = 4
<strong>Output:</strong> true
<strong>Explanation:</strong> n is already a perfect square, Alice can win with one move, removing 4 stones (4 -&gt; 0).
</pre>

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

<ul>
	<li><code>1 &lt;= n &lt;= 10<sup>5</sup></code></li>
</ul>

class Solution {
public:
    bool solve(int n,int flag,vector<vector<int>> &dp){
        if(n == 0){
            if(flag == true){
                return false;
            }
            return true;
        }
        if(dp[flag][n] != -1) return dp[flag][n];
        
        bool ans = false; 
        for(int i = 1;i<=sqrt(n);i++){
            if(n - i*i >= 0){
                if(solve(n-i*i,!flag,dp) == true) return true;
            }
        }
        return  dp[flag][n] = ans;
    }
    bool winnerSquareGame(int n) {
        vector<vector<int>> dp(2,vector<int>(n+1,0));

        //Bob will play
        dp[0][0] = false;
        //Alice will play
        dp[1][0] = false;

        for(int i = 1;i<=n;i++){
            for(int j = 0;j<=1;j++){
                for(int k = 1;k*k<=i;k++){
                    if(i - k*k >= 0){
                        if(j == 0){
                            if(dp[1][i-k*k] == false){
                                dp[j][i] = true;
                                break;
                            }
                        }else{
                            if(dp[0][i-k*k] == false){
                                dp[j][i] = true;
                                break;
                            }
                        }
                    }
                }
            }
        }
        return dp[1][n];
    }
};
10789