LeetCode:Nim Game

落爺英雄遲暮 提交于 2019-12-06 02:41:56

1、题目名称

Nim Game(尼姆博弈)

2、题目地址

https://leetcode.com/problems/nim-game/

3、题目内容

英文:

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、解题方法1

网上已经有了很多对尼姆博弈问题的介绍,如维基百科页面:

https://en.wikipedia.org/wiki/Nim

解题Java代码如下:

/**
 * LeetCode 292 - Nim Game
 * @FileName Solution.java
 * @FileAuthor Tsybius
 * @DateTime 2015年12月20日 下午10:47:54
 */
public class Solution {
    
    /**
     * 计算尼姆博弈当前情况下是否必胜
     * @param n
     * @return
     */
    public boolean canWinNim(int n) {
        if (n <= 0) {
            return false;
        } else {
            return n % 4 != 0; 
        }
    }
}

另一种解法是讨论区大牛给出的方法,采用位运算解决本问题。

/**
 * LeetCode 292 - Nim Game
 * @FileName Solution.java
 * @FileAuthor Tsybius
 * @DateTime 2015年12月20日 下午10:54:12
 */
public class Solution {
    
    /**
     * 计算尼姆博弈当前情况下是否必胜
     * @param n
     * @return
     */
    public boolean canWinNim(int n) {
        if (n <= 0) {
            return false;
        } else {
            return n >> 2 << 2 != n;
        }
    }
}

END

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!