[LeetCode] 292. Nim Game

You are playing the following Nim Game with your friend:
Initially, there is a heap of stones on the table.
You and your friend will alternate taking turns, and you go first.
On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.
The one who removes the last stone is the winner.
Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.

Example 1:
Input: n = 4
Output: false
Explanation: These are the possible outcomes:

  1. You remove 1 stone. Your friend removes 3 stones, including the last stone. Your friend wins.
  2. You remove 2 stones. Your friend removes 2 stones, including the last stone. Your friend wins.
  3. You remove 3 stones. Your friend removes the last stone. Your friend wins.
    In all outcomes, your friend wins.

Example 2:
Input: n = 1
Output: true

Example 3:
Input: n = 2
Output: true

Constraints:
1 <= n <= 231 - 1

Nim 游戏。

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

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

思路

这是一道博弈论的题。我们看一下规律。

  1. 如果石子数量在 1 - 3 之间,那么先手获胜
  2. 如果石子数量 = 4,先手无论拿几个石子,后手都会获胜,因为后手可以拿到最后一个石子
  3. 如果石子数量在 5 - 7 之间,那么先手可以通过控制剩余石子数 = 4 来决定自己拿几个石子,只要剩余石子个数 = 4,那么还是先手获胜。比如一开始是 7 个石子,先手拿 3 个,剩余石子个数 = 4,此时无论后手怎么拿,最后一个石子还是会被先手拿到
  4. 如果石子数量 = 8,先手无论拿几个石子,后手都会获胜,因为先手拿完之后,石子数量介于 5 - 7 之间,只要后手确保自己拿完之后剩余石子数量 = 4,后手就会获胜了,等同于 case 2。

所以只要石子数量不是 4 的倍数,先手获胜。
引用

复杂度

时间O(1)
空间O(1)

代码

Java实现

1
2
3
4
5
class Solution {
public boolean canWinNim(int n) {
return n % 4 != 0;
}
}

[LeetCode] 292. Nim Game
https://shurui91.github.io/posts/2832354358.html
Author
Aaron Liu
Posted on
February 3, 2024
Licensed under