[leetcode] 1025. Divisor Game

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. 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]

参考文献

[LeetCode] Distribute Candies 分糖果

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

农民小飞侠

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值