LeetCode實戰:Nim 遊戲

背景


題目英文

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.

Example:

Input: 4
Output: false 
Explanation: 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.

題目中文

你和你的朋友,兩個人一起玩 Nim 遊戲:桌子上有一堆石頭,每次你們輪流拿掉 1 - 3 塊石頭。 拿掉最後一塊石頭的人就是獲勝者。你作爲先手。

你們是聰明人,每一步都是最優解。 編寫一個函數,來判斷你是否可以在給定石頭數量的情況下贏得遊戲。

示例:

輸入: 4
輸出: false 
解釋: 如果堆中有 4 塊石頭,那麼你永遠不會贏得比賽;
    因爲無論你拿走 1 塊、2 塊 還是 3 塊石頭,最後一塊石頭總是會被你的朋友拿走。

算法實現

每一回合都必須拿石子,所以當到誰的回合還剩下4個石子,那麼誰就輸了。

  • [1,3]先手贏
  • [4]後手贏
  • [5,7]先手贏,因爲你可以使到對方回合時是剩下4個石子
  • [8]後手贏,此時對方可以使在你的回合時剩下4個石子
  • 以次類推可以發現當n爲4的倍數時先手總會輸
public class Solution
{
    public bool CanWinNim(int n)
    {
        return (n % 4 != 0);
    }
}

實驗結果

  • 狀態:通過
  • 60 / 60 個通過測試用例
  • 執行用時: 56 ms, 在所有 C# 提交中擊敗了 82.41% 的用戶
  • 內存消耗: 13.6 MB, 在所有 C# 提交中擊敗了 5.17% 的用戶

提交結果


相關圖文

1. “數組”類算法

2. “鏈表”類算法

3. “棧”類算法

4. “隊列”類算法

5. “遞歸”類算法

6. “字符串”類算法

7. “樹”類算法

8. “哈希”類算法

9. “搜索”類算法

10. “動態規劃”類算法

11. “回溯”類算法

12. “數值分析”類算法

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