LeetCode值Nim Game

周末刷知乎的时候,有人说leetcode.com网站上的练习题非常适合准备跳槽的人,虽然我不准备跳槽,但多见识一些总没有错,抱着好玩的心态,按照难度的排了顺序,开始做题。

这就是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时,返回值为你是否获胜,true为获胜,false为失败。

举例,如果这里有4个石子,那么你将会输掉游戏,因为无论你移除1或2或3个石子之后,最后的石子都会被你的朋友拿走。


规则以及解题要求都已经清楚了,那么下面我来讲一下这道题的关键点:一、你和你的朋友足够聪明;二、每人每次只能拿1-3个;三、当N为4时,你一定是失败的。

对数字敏感的同学应该已经看出端倪了,这是一道很简单的算法题,所以就直接公布答案了:当N > 0 and N < 4时,返回true;当N > 4 且 N % 4 的值不为零时,返回值为true,否则返回false。意思就是,除了n为4的倍数以外的情况你会输,其他情况你都是可以赢的。

这里说一下思路,因为当余数为1-3时,你可以将场面控制成剩余石子数为4的倍数。

PS:老话说的话,先下手为强呐!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值