【LeetCode】292 Nim Games (java实现)

版权声明:文章欢迎转载,但请注明出处。 https://blog.csdn.net/styshoo/article/details/50212593

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块石头。谁最后一次取走剩余的石头,谁就取得了胜利。由你先取石头。
假设你和你的朋友都很聪明,有最优的策略来获取胜利。写一个方法来判断在给定石头个数的情况下,你是胜利还是失败。
比如,如果总共有4块石头,那么无论你一次性取1,2,还是3块石头,你的朋友都会取最后的几块石头。*
    通过给出的示例,如果总共有4块石头,我就肯定失败。那么,如果是4+[1,2,3]这样范围的数字,即5,6,7时,我就一定会胜利,因为我可以取[1-3]块石头,使得剩下的石头个数为4块给朋友,那么他就失败了。同理,如果石头总数是8,那么我就失败了,不管怎么取,剩下的石头个数范围是[5-7],就和上面的情况一样了。
    综上所述,这看起来就像是一种动态规划的思路。4失败;[5-7]成功;8失败;[9-11]成功……但根据表象来分析,最终的代码只需要一句话:

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

    在我看来这道题更像是一道智力题,而不是算法题。

没有更多推荐了,返回首页