LeetCode*292. Nim Game

LeetCode题目链接

题目:

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.

答案:

public:
    bool canWinNim(int n) {
        if (n < 4) {
            return true;
        }
        
        return n % 4 != 0;
    }
};

解析:

主要是将题意转化一下,很快发现只要是4的倍数,都不可能会赢。(如果对方不蠢的话)。想赢的话,只要将剩下的石头个数保持在4的倍数就可以了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,528评论 5 6
  • Nim Game 题目描述: You are playing the following Nim Game wit...
    Nemo_WangCN阅读 205评论 0 0
  • 外公走了。 中午的时候手机显示了弟发来的信息今天的那个时候,我们宿舍处于断电状态,看到信息,我并没有立即的悲伤。和...
    黄超风阅读 431评论 0 1
  • 捆绑无处不在,所有的拥有都是一种捆绑,“有”是捆绑,对”无“和”空“的追求也是捆绑。 为什么我支持解雇在简书日更的...
    世涂花开阅读 179评论 0 0
  • 春无力 扶你香肩手无力 风中泣 离愁话别 口已讷 柳绿的时节口已讷 滑落我的手 颤栗不止 我心里呼唤 你我的誓言 ...
    麦动文阅读 319评论 12 23