LeetCode-Nim Game

  • Problem:

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.

  • analysis:

题目指的是有一堆石头,你和你的朋友每次最多拿走3个,轮流拿,最后一个拿走石头而没有剩余的人获胜。

其实这是一个尼姆堆游戏,大家可以考虑,对于先手来说:

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个后手就剩3个,先手取2个后手就剩2个,先手取3个后手就剩1个,总之4个时先手lose但是如果是5个先手只要拿走一个后手就面对了4个必输的局面,如果6个先手拿走2个后手同样面对4个必输的局面,如果是7个先手拿走3个后手同样面对4个必输的局面,但是8个先手不论拿1个,2个,3个会使后手面对7个,6个,5个刚刚验证的必赢局面。

循环下去会发现只要是4的倍数先手就必输,其余情况先手必赢。


那么我们分析如果最多拿4个数呢,是否只要堆的个数是5的倍数先手必输,其余情况先手必赢?如果最多拿5个数呢,是否只要堆的个数是6的倍数先手必输,其余情况先手必赢?......   答案是肯定的


这就考虑到斐波那契尼姆堆的问题:要求后手拿的个数不能超过先手的一倍         

 结果:只要堆的个数是个斐波那契数(即1,1,2,3,5,8,13,21,34,5589,144, 233,377,610,987.....中某一个)后者取胜,否则先手胜。那么如果是斐波那契尼姆堆是1000个数,先手要赢只要先拿走13个数就可以赢,因为1000-13=987是斐波那契数。

  • anwser:

public class Solution {
    public boolean canWinNim(int n) {
        if(n%4==0) return false;
        else return true;
    }
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值