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?

链接: http://leetcode.com/problems/nim-game/

题解:

看来我的推测是对的。jianchao.li真的加了很多很多数学有关的趣题...这个也是很有意思,第一次接触是在小时候看古畑任三郎第一季最后一集里老爷和数学家(毛利小五郎)对弈,玩的就是这个游戏。关键就是4的倍数一定是false,所以我们直接返回结果。

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

二刷:

Java:

Time Complexity - O(1), Space Complexity - O(1)

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

三刷:

Java:

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

Reference:

https://leetcode.com/discuss/63725/theorem-all-4s-shall-be-false

https://leetcode.com/discuss/63978/one-line-o-1-solution-and-explanation

原文地址:https://www.cnblogs.com/yrbbest/p/5042259.html