[LeetCode] NO.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.

[题目解析]: 根据题目进行分析,当有4个石头的时候,无论你拿1,2还是3个,对手都可以最后一个拿完,你永远不会赢。

        依次类推,当有5个石头的时候,你拿1个,留给对方4个,对方必输;当有6个石头的时候,你拿2个,对方必输;当有7个石头的时候,你拿3个,对方必输。而当有8个石头的时候,你无论拿1,2,还是3个,都留给对方7,6,5三种,对方都必赢。继续类推呢,发现规律了吗?n%4等于0的时候,你必输,其他情况你都可以赢。

        

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

 

posted @ 2016-08-13 11:52  三刀  阅读(124)  评论(0编辑  收藏  举报