LeetCode:Nim Game

先上題目鏈接: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.

題目大意就是給你一堆石頭,每次可以從中拿出1~3塊,兩個人輪流拿,拿到最後一塊石頭的人獲勝。現在有 n 塊石頭,由你先拿,請快速判斷你能否獲勝。

f(n) 表示有 n 塊石頭時的獲勝情況(必輸/必贏),由於你拿了之後,接着是對方拿,所以得到公式:

f(n)=![f(n1)&&f(n2)&&f(n3)]

由於 f(1)=f(2)=f(3)=true ,結合公式可以發現這是一個長度爲4的循環,得到這樣一個關係:
f(n)={false,true,if n mod 4 is zeroother conditions

代碼如下:

public class Solution {
    public boolean canWinNim(int n) {
        boolean result = false;
        if (n < 1) {
            return false;
        } 

        if ((n%4) != 0) {
            result = true;
        }

        return result;
    }
}



我的作業部落鏈接:Nim Game

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章