LeetCode Algorithms 292. Nim Game 题解

来源:互联网 发布:c语言memset头文件 编辑:程序博客网 时间:2024/05/21 06:41

题目:
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-3个石头,所以当石头数为1,2,3的时候,是稳赢的。当石头数为4的时候,因为对方也很聪明,无论我选择拿1个2个还是3个石头,对方都能在下一次选1-3个石头来击败我。因此石头数是4的时候我是稳输的。
基于以上思考,不难发现,只需让对方选石头数的时候为4个,则我必胜。为了达到这个目的,5-7个石头是可以接受的,但8个石头的时候,我怎么选,都无法让对手拿到4个石头,因此8个石头也是必输的。同理可得,当12个石头的时候,我也是必输的。

猜测一下,当有n=4k(k=0,1,2,3…)个石头的时候,我是必输的。
因为是我开始拿石头,无论我拿1个2个还是3个,对方都可以拿4-我拿的数量的个数,让剩下的石头数变成4(k-1)个,这样最后剩下4个石头的时候一定轮到我拿,我是必输的。
当n=4k+1/2/3的时候,我先拿1-3个使得剩下的个数为4K个,那么对手必输。
因此只需验证n是否是4的倍数,最开始是return n%4 == 0?false:true;,这样提交之后发现,只击败了1%的人,想了下要如何优化,发现4这个数是可以从二进制方向入手的,4的倍数的二进制后两位永远是00,因此与二进制的11做&操作,如果是0则是4的倍数,否则不是。最终代码为return n&3;不过这个代码也只击败了39%的人,查看solution也没有发现有更快的代码。。。

0 0
原创粉丝点击