LeetCode ---- Nim Game (Java/Lua 實現)

題目:

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.

大概翻譯下:
桌上有一堆石頭,你和你朋友玩遊戲,規則如下,你和你的朋友(另一個人,總共 2 人)輪流每次拿走 1-3 塊石頭,誰拿走最後的石頭就是勝者。你將第一個開始拿走石頭。
設計一個程序分析總共多少塊石頭的情況下你能贏得比賽。
比如,如果有 4 塊石頭,那麼你永遠不可能贏得比賽,因爲不管你是拿 1 塊、2塊,還是3塊,最後的時候都是你朋友拿走的。

提示:如果堆中有 5 個石頭,怎麼樣取你才能獲勝?

5 塊的時候,你先拿 1 塊,然後剩下 4 塊,根據題目中的樣例,你會發現在剩 4 塊時候,誰先拿誰就輸了。

當n∈[1,3]時,先手必勝。

當n == 4時,無論先手第一輪如何選取,下一輪都會轉化爲n∈[1,3]的情形,此時先手必負。

當n∈[5,7]時,先手必勝,先手分別通過取走[1,3]顆石頭,可將狀態轉化爲n == 4時的情形,此時後手必負。

當n == 8時,無論先手第一輪如何選取,下一輪都會轉化爲n∈[5,7]的情形,此時先手必負。

歸納分析,在石頭爲 4 的倍數時,先手就會失敗。


Java 語言實現:

public static boolean canWinNim(int n) {
    if (n % 4 == 0)
        return false;
    return true;
}


Lua 語言實現:
 function canWinNim(nums)
     assert(type(nums) == "number", "arguments num is not a number")
     return nums % 4 ~= 0
 end

 print(canWinNim(1))



注意到 lua 語法:
  • 非是 ~,而不是 Java 中的 !
  • Lua 動態類型語言,數值纔是有類型的,變量無類型(Java 傳入參數 int n,而 lua 直接 nums)

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