292. Nim Game

来源:互联网 发布:json转java实体对象 编辑:程序博客网 时间:2024/06/07 07:25

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,2,3块石头的时候,自己先拿,一定会赢。有4块石头,自己不论拿什么都会输。

同时可以看出,而当有4块石头的时候,先拿的一定会输。

往后可以分析出,当有5,6,7块石头的时候,只要自己拿走一些石头使得剩下的数目为4,那么此时轮到对方先拿,对方会输。当有8块石头的时候,自己首先拿1-3块,对方会拿适宜的数目使剩下4块,这时轮到自己,自己会输。

同理,继续往后,每当到4的倍数,自己就会输。

代码如下:

class Solution {public:    bool canWinNim(int n) {        return n%4;            }};


0 0
原创粉丝点击