Alice and Bob take turns playing a game, with Alice starting first.
Initially, there are n
stones in a pile. On each player's turn, that player makes a move consisting of removing any non-zero square number of stones in the pile.
Also, if a player cannot make a move, he/she loses the game.
Given a positive integer n
. Return True
if and only if Alice wins the game otherwise return False
, assuming both players play optimally.
Example 1:
Input: n = 1 Output: true Explanation: Alice can remove 1 stone winning the game because Bob doesn't have any moves.
Example 2:
Input: n = 2 Output: false Explanation: Alice can only remove 1 stone, after that Bob removes the last one winning the game (2 -> 1 -> 0).
Example 3:
Input: n = 4 Output: true Explanation: n is already a perfect square, Alice can win with one move, removing 4 stones (4 -> 0).
Example 4:
Input: n = 7 Output: false Explanation: Alice can't win the game if Bob plays optimally. If Alice starts removing 4 stones, Bob will remove 1 stone then Alice should remove only 1 stone and finally Bob removes the last one (7 -> 3 -> 2 -> 1 -> 0). If Alice starts removing 1 stone, Bob will remove 4 stones then Alice only can remove 1 stone and finally Bob removes the last one (7 -> 6 -> 2 -> 1 -> 0).
Example 5:
Input: n = 17 Output: false Explanation: Alice can't win the game if Bob plays optimally.
Constraints:
1 <= n <= 10^5
題目難度:中等
題目大意:Alice和Bob輪流玩一個遊戲,Alice先。一開始,堆裏有n個石頭,輪到某個人的時候,它可以移除堆裏的平方數(就是1個,4個,9個...)個石頭。如果輪到某人的時候,它不能移除石頭,那麼它就輸了。
給定一個正整數n,如果Alice贏了,函數返回True,否則返回False。前提是兩個人都能玩得很好。
思路:兩個人都能玩的很好,都是最優策略,假定某個人面對n個石頭的時候,F[n] = True表示贏, 否則爲False.
當有n個石頭的時候,輪到Alice移除,她可以選擇移除$1^2$, $2^2$, ..., ${\lfloor \sqrt{n} \rfloor}^2$個,假如Alice 移除 $1^2$個石頭,接下來剩下$n - 1$個石頭,Bob來移除,如果
F[n - 1] = True, 表明,n個石頭,Alice移除1個的話就輸了,如果F[n - 1] = False,表明Alice贏了,這是一個子問題結構。
Alice在面對n個石頭的時候,也可以選擇移除4個,那麼只要F[n - 4] = False, 那麼Alice也能贏。
F[n] = (1 - F[n - 1]) | (1 - F[n - 4]) | ... | (1 - F[n - ${\lfloor \sqrt{n} \rfloor}^2$] (或F[n - 1],F[n -4] ....其中有一個爲0,則F[n] = 1)
代碼一:動態規劃
C++代碼
class Solution { public: bool winnerSquareGame(int n) { vector<bool> f(n + 1, 0); for (int i = 1; i < n + 1; ++i) { // f[i] = 0; for (int j = 1; j * j <= i; ++j) { if (f[i - j * j] == false) { f[i] = true; break; } // f[i] = f[i] | (1 - f[i - j * j]); // if (f[i] == 1) // break; } } return f[n]; } };
python3代碼:
1 class Solution: 2 def winnerSquareGame(self, n: int) -> bool: 3 dp = [False] * (n + 1) 4 for i in range(1, n + 1): 5 j = 1 6 while j * j <= i: 7 if dp[i - j * j] == False: 8 dp[i] = True 9 break 10 j += 1 11 return dp[n] 12
時間複雜度:$O(n \sqrt{n})$, 空間複雜度:$O(n)$
思路二:記憶化的遞歸 (自己實現)