292. Nim Game

题目

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.

Hint:

  1. If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

##分析 每次移走1~3个石头,我先来,谁移走最后一块石头谁赢,根据石头总数求出我是否会赢

若n=1、2、3;赢

若n=4,我1--敌3,我2--敌2,我3--敌1;输

若n=5,我1--敌1--我3,我1--敌2--我2,我1--敌3--我1;赢

若n=6,我2--敌1--我3,我2--敌2--我2,我2--敌3--我1;赢

若n=7,我3--敌1--我3,我3--敌2--我2,我3--敌3--我1;赢

若n=8,我1--敌3--剩4,我2--敌2--剩4,我3--敌1--剩4;输

……

若n为4的倍数,输;否则,赢。

解答

解法1:(我)(0ms)

public class Solution {
    public boolean canWinNim(int n) {
        return n % 4 != 0;
    }
}
原文地址:https://www.cnblogs.com/xuehaoyue/p/6412587.html