292. Nim 游戏(javascript)292. Nim Game

你和你的朋友,两个人一起玩 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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值