★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公眾號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: https://www.cnblogs.com/strengthen/p/10704584.html
➤如果鏈接不是山青詠芝的博客園地址,則可能是爬取作者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持作者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
Alice and Bob take turns playing a game, with Alice starting first.
Initially, there is a number N on the chalkboard. On each player's turn, that player makes a move consisting of:
- Choosing any
xwith0 < x < NandN % x == 0. - Replacing the number
Non the chalkboard withN - x.
Also, if a player cannot make a move, they lose the game.
Return True if and only if Alice wins the game, assuming both players play optimally.
Example 1:
Input: 2
Output: true Explanation: Alice chooses 1, and Bob has no more moves.
Example 2:
Input: 3
Output: false Explanation: Alice chooses 1, Bob chooses 1, and Alice has no more moves.
Note:
1 <= N <= 1000
愛麗絲和鮑勃一起玩游戲,他們輪流行動。愛麗絲先手開局。
最初,黑板上有一個數字 N 。在每個玩家的回合,玩家需要執行以下操作:
- 選出任一
x,滿足0 < x < N且N % x == 0。 - 用
N - x替換黑板上的數字N。
如果玩家無法執行這些操作,就會輸掉游戲。
只有在愛麗絲在游戲中取得勝利時才返回 True,否則返回 false。假設兩個玩家都以最佳狀態參與游戲。
示例 1:
輸入:2 輸出:true 解釋:愛麗絲選擇 1,鮑勃無法進行操作。
示例 2:
輸入:3 輸出:false 解釋:愛麗絲選擇 1,鮑勃也選擇 1,然后愛麗絲無法進行操作。
提示:
1 <= N <= 1000
1 class Solution { 2 func divisorGame(_ N: Int) -> Bool { 3 return N % 2 == 0 4 } 5 }
Runtime: 4 ms
1 class Solution { 2 func divisorGame(_ N: Int) -> Bool { 3 var N = N 4 var alice:Bool = false 5 for x in 1..<N 6 { 7 alice.toggle() 8 if N % x == 0 9 { 10 N -= x 11 } 12 } 13 return alice 14 } 15 }
44ms
1 class Solution { 2 func divisorGame(_ N: Int) -> Bool { 3 var dp = [Int:Bool]() 4 dp[1] = false 5 dp[2] = true 6 7 var i = 3 8 while i <= N{ 9 var x = i 10 var lose = false 11 dp[i] = false 12 repeat{ 13 x -= 1 14 if (i%x == 0 && dp[i-x]! == false){ 15 dp[i] = true 16 } 17 }while x > 1 18 19 i += 1 20 } 21 22 return dp[N]! 23 } 24 }
