<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:
  def winnerSquareGame(self, n: int) -> bool:
    squares = []
    i = 1
    while True:
      num = i*i
      if num > n: break
      squares.append(num)
      i += 1

    # dp[(i, is_player1)]: we have i stones, and is_player1.
    dp = {}

    def _helper(i, is_player1):
      if i == 0:
        if is_player1:
          return False, True
        return True, False

      state = (i, is_player1)
      if state in dp:
        return dp[state]
      max_sc = False
      other_sc = True
      for x in squares:
        next_i = i - x
        if next_i < 0:
          break
        # print("i: ", i, ", x: ", x, ", next_i: ", next_i, ", cur_sum: ", cur_sum)
        sc1, sc2 = _helper(next_i, not is_player1)
        if is_player1:
          if sc1:
            max_sc = sc1
            other_sc = sc2
            break
        else:
          if sc2:
            max_sc = sc2
            other_sc = sc1
            break
      if is_player1:
        res = (max_sc, other_sc)
      else:
        res = (other_sc, max_sc)
      # print("\n--\nis_player1: ", is_player1, ", i: ", i, ", piles[i:]: ", piles[i:], ", m: ", m, ", res: ", res)
      dp[state] = res
      return dp[state]

    sc1, sc2 = _helper(n, True)
    return sc1
58201