LeetCode 题解工作台

Nim 游戏

你和你的朋友,两个人一起玩 Nim 游戏 : 桌子上有一堆石头。 你们轮流进行自己的回合, 你作为先手 。 每一回合,轮到的人拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。 假设你们每一步都是最优解。请编写一个函数,来判断你是否可以在给定石头数量为 n 的情况下赢得游戏。如果可以赢,返…

category

3

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 数学·结合·brainteaser

bolt

答案摘要

第一个得到 的倍数(即 能被 整除)的将会输掉比赛。 证明:

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 数学·结合·brainteaser 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

你和你的朋友,两个人一起玩 Nim 游戏

  • 桌子上有一堆石头。
  • 你们轮流进行自己的回合, 你作为先手 
  • 每一回合,轮到的人拿掉 1 - 3 块石头。
  • 拿掉最后一块石头的人就是获胜者。

假设你们每一步都是最优解。请编写一个函数,来判断你是否可以在给定石头数量为 n 的情况下赢得游戏。如果可以赢,返回 true;否则,返回 false

 

示例 1:

输入:n = 4
输出:false 
解释:以下是可能的结果:
1. 移除1颗石头。你的朋友移走了3块石头,包括最后一块。你的朋友赢了。
2. 移除2个石子。你的朋友移走2块石头,包括最后一块。你的朋友赢了。
3.你移走3颗石子。你的朋友移走了最后一块石头。你的朋友赢了。
在所有结果中,你的朋友是赢家。

示例 2:

输入:n = 1
输出:true

示例 3:

输入:n = 2
输出:true

 

提示:

  • 1 <= n <= 231 - 1
lightbulb

解题思路

方法一:找规律

第一个得到 44 的倍数(即 nn 能被 44 整除)的将会输掉比赛。

证明:

  1. n<4n \lt 4 时,第一个玩家可以直接拿走所有的石头,所以第一个玩家将会赢得比赛。
  2. n=4n = 4,无论第一个玩家选择 1,2,31, 2, 3 哪个数字,第二个玩家总能选择剩下的数字,所以第一个玩家将会输掉比赛。
  3. 4<n<84 \lt n \lt 8 时,即 n=5,6,7n = 5, 6, 7,第一个玩家可以相应地将数字减少为 44,那么 44 这个死亡数字给到了第二个玩家,第二个玩家将会输掉比赛。
  4. n=8n = 8,无论第一个玩家选择 1,2,31, 2, 3 哪个数字,都会把 4<n<84 \lt n \lt 8 的数字留给第二个,所以第一个玩家将会输掉比赛。
  5. ...
  6. 依次类推,当玩家拿到 nn 这个数字,且 nn 能被 44 整除,他将会输掉比赛,否则他将赢得比赛。

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def canWinNim(self, n: int) -> bool:
        return n % 4 != 0
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    A correct approach identifies the modulo 4 pattern for optimal play.

  • question_mark

    The candidate should recognize the game theory basis for the solution.

  • question_mark

    Candidates who try brute force simulations instead of a mathematical solution may need further guidance.

warning

常见陷阱

外企场景
  • error

    Overcomplicating the solution by simulating all possible moves instead of using the modulo 4 strategy.

  • error

    Failing to recognize that the winning and losing positions are based on multiples of 4.

  • error

    Misunderstanding the alternating nature of the game and assuming a winning strategy when n % 4 == 0.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if players can remove 1, 2, or 3 stones, but the first player can remove up to 4 stones?

  • arrow_right_alt

    How would the game change if there were more than 3 players, all taking turns to remove stones?

  • arrow_right_alt

    What happens if the first player can only remove 1 stone per turn?

help

常见问题

外企场景

Nim 游戏题解:数学·结合·brainteaser | LeetCode #292 简单