LeetCode 292. 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.

 


题目标签:Brainteaser

  这道题目给我们一个数字,代表是石头的数量,让我们判断,能赢还是没机会赢,这里假设两个玩家都是有最精确的策略。还有就是,游戏里我是先走的那个,而且每个人一次只能取1或者2或者3个石头。

  那我们来举例子看一下:

       n  我

  1  win

  2  win

  3  win

  4  lose

  5  win

  6  win

  7  win

  8  lose

  9  win

  10  win

  11  win

  12  lose

  我们看到,只有在4的倍数的情况下,我们会输。来分析一下,当给的数字是4的倍数时候,无论我们怎么拿,拿1,2,3。对方都能够化解,然后返回给我们一个4的倍数,这里的策略就是,谁能给对方留下一个4的倍数,就一定能赢。换一句话说,就是谁拿到4的倍数一定会输(除非对方失误)。在不是拿到4的倍数的情况下,只要每一次留给对方4的倍数,我们就可以一直保持到倒数第三轮,给对方4, 对方无论拿走1,2,3, 我们都能一次拿完。

 

 

Java Solution:

Runtime beats 6.87% 

完成日期:07/10/2017

关键词:Brainteaser

关键点:因为我们只能拿1,2,3块石头,所以4这个数字就是关键

 

 1 public class Solution 
 2 {
 3     public boolean canWinNim(int n) 
 4     {
 5         if(n % 4 == 0)
 6             return false;
 7         else
 8             return true;
 9     }
10 }

参考资料:

http://www.cnblogs.com/grandyang/p/4873248.html

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

转载于:https://www.cnblogs.com/jimmycheng/p/7148670.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值