292.Nim棋牌(javascript)292.NimGame

原创
小哥 3年前 (2022-11-10) 阅读数 7 #大杂烩

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

桌子上有一堆石头。
你轮流轮流打球, 你是第一手 。
每一回合,回合都被取消 1 - 3 块石头。
拿下最后一块石头的人是赢家。
假设你在每一步都是最佳的。请写一个函数来确定是否可以给你石头的数量。 n 在赢得比赛的情况下。如果你能赢,就回来。 true; 否则,返回 false 。

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.

示例 1:

输入:n = 4
输出:false 
说明:以下是可能的结果:
1. 移除1一块石头。你的朋友搬走了3一一块石头,包括最后一块。你的朋友赢了。
2. 移除2一块石头。你的朋友已删除2一一块石头,包括最后一块。你的朋友赢了。
3. 你移走3一块石头。你的朋友拿走了最后一块石头。你的朋友赢了。
在所有的结果中,你的朋友是赢家。

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.

示例 2:

输入:n = 1
输出:true
Input: n = 1
Output: true

示例 3:

输入:n = 2
输出:true
Input: n = 2
Output: true

问题解决流程:
来源: https://leetcode-cn.com/problems/nim-game/solution/gong-shui-san-xie-noxiang-xin-ke-xue-xi-wmz2t/
不可能有太多的食物-_-

在我们知道博弈论的结论之前,我们可以通过寻找规律得到猜想,然后从【在什么情况下,第一手会处于获胜状态】的角度进行分析。
根据问题的含义,我们试图讨论小规模数据的情况:

  1. 如果情况首先发生,石头的数量是1到3],那么新手将获胜;
  2. 如果情况首先发生,石头的数量是4],然后第一手做出决定(无论是哪种决定),交给后者的情况是[石头的数量]1到3],此时反手会赢,第一手会输4如果是,那么第一手将被击败);
  3. 如果情况首先发生,石头的数量是5到7],则可以控制第一只手来选择石头的数量,从而使后一只手在石头的数量上。4]形势(此时反手会输),此时第一手会赢;
  4. 如果情况首先发生,石头的数量是8],因为每次只能选择1到3一块石头,所以反手的情况是5到7,根据流程3,我们知道此时第一手会输;

    这里我们推测 当起始情况下的石头数量为 4 乘数,则第一手会输,否则第一手会赢。 n % 4 != 0 何时,第一手将获胜)。

    var canWinNim = function (n) { return n % 4 != 0

    };

leetcode: https://leetcode-cn.com/problems/nim-game/

版权声明

所有资源都来源于爬虫采集,如有侵权请联系我们,我们将立即删除