292. Nim Game

题目:Nim Game

原题链接
You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.
Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.
For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.
简单翻译一下:一个小游戏,给定n块石子,每个人(一共你和对手两个人)每次只能拿1~3块石子,你先开始拿,能够拿走最后一块石子的人获胜,题目要求想办法判断在n块石子的情况下你能不能一定获胜(双方都比较聪明,不会自寻死路= =)。举例:如果一共有4块石子,无论如何你都是必输之局= =。

很明显,只有不超过3块石子的情况下你肯定赢了。。。
题目的举例给的很好,4块石子,在自己先手的情况下只能拿1或者2或者3块石子,对应的剩余石子数量是3或者2或者1,这样的话对手肯定可以拿走最后一块石子,所以这是一个必输之局。以这个为基础来想的话,只要我们能想办法凑到在对手的轮次时只剩下4块石子,那我们就稳赢了,那么如何凑呢?从n=5开始先试着枚举一下胜负情况,这边简单列出一个表格:

n胜负结果第一拿的个数
5win1
6win2
7win3
8lose#
9win1
10win2
11win3
12lose#

观察一下可以发现,这个里面存在一个“轮回”,即4个一轮回,当n是4的倍数的时候,这是稳输的,但当n不是4的倍数的时候,你总是可以想办法让对手开始拿石子的时候剩余数量是4的倍数,所以结论就出来了,如果n是4的倍数,那就是必输之局,如果不是,那就是必赢了,代码如下:

class Solution {
public:
    bool canWinNim(int n) {
        return n & 3; // 和3(0011)相与,只有n为4的倍数的时候结果是0
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值