【LeetCode】292 Nim Games (java实现)

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.

题目要求:
*和朋友取物游戏,有一堆石头,一次只能去1到3块石头。谁最后一次取走剩余的石头,谁就取得了胜利。由你先取石头。
假设你和你的朋友都很聪明,有最优的策略来获取胜利。写一个方法来判断在给定石头个数的情况下,你是胜利还是失败。
比如,如果总共有4块石头,那么无论你一次性取1,2,还是3块石头,你的朋友都会取最后的几块石头。*
    通过给出的示例,如果总共有4块石头,我就肯定失败。那么,如果是4+[1,2,3]这样范围的数字,即5,6,7时,我就一定会胜利,因为我可以取[1-3]块石头,使得剩下的石头个数为4块给朋友,那么他就失败了。同理,如果石头总数是8,那么我就失败了,不管怎么取,剩下的石头个数范围是[5-7],就和上面的情况一样了。
    综上所述,这看起来就像是一种动态规划的思路。4失败;[5-7]成功;8失败;[9-11]成功……但根据表象来分析,最终的代码只需要一句话:

public boolean canWinNim(int n) {    
    return n % 4 != 0 ;
}

    在我看来这道题更像是一道智力题,而不是算法题。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值