292. Nim Game

来源:互联网 发布:淘客cms微信系统 编辑:程序博客网 时间:2024/06/04 01:14

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.

假设还有n个石头,而且玩家B最后拿,那么玩家B可以拿的石头是1,2,3个,玩家A可以拿的情况有以下9种:

B (x-1) -> A: (x-2), (x-3), (x-4)B (x-2) -> A: (x-3), (x-4), (x-5)B (x-3) -> A: (x-4), (x-5), (x-6)

那么f(x)的状态就是:

f(x) = (f(x-2)&&f(x-3)&&f(x-4)) || (f(x-3)&&f(x-4)&&f(x-5)) || (f(x-4)&&f(x-5)&&f(x-6))
这里可以发现,如果f(x-4)是false,那么B就不会赢。

初始条件n=1,2,3时,A都可以赢,4时A必输。按照上面的想法,n=5,6,7时,A可以赢,8时A必输。所以代码如下:

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

0 0