Description
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 x with 0 < x < N and N % x == 0.
- Replacing the number N on the chalkboard with N - 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,两个人玩除数游戏,Alice选择一个能够被n(不包含n)整除的数x,然后Bob选择一个能被n-x整除的数,依次选择,直到不能知道到一个整除的数位置。
我看了一下动态规划的思路,首先n=0表示没有数可以选择,Alice输,n=1Alice也不能选择,Alice也算输,n=2 Alice赢,n=3 Alice输…。
- 我们定义一个dp数组,长度为N+1,dp[i]表示在当前的数位i的情况下,Alice输赢情况,dp[i]的情况依赖于dp[i-x],其中i能够整除x,剩下的就是遍历找出能够被i整除的x,且为输的情况,上一步为输,当前就为赢了,如果找不到就只能是输了,所以dp初始化为False。
这道题还能找规律,N为偶数,Alice肯定赢,否则肯定会输。
代码
class Solution:
def divisorGame(self, N: int) -> bool:
dp=[False]*(N+1)
for i in range(1,N+1):
for j in range(i):
if(j==0):
continue
elif(i%j==0 and dp[i-j]==False):
dp[i]=True
break
return dp[N]