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.

題目大意:

你正在和朋友玩下面的Nim遊戲:桌子上有一堆石頭,每一次你們輪流取1至3顆石頭。最後一個取走石頭的人就是贏家。第一輪由你先取。

你們倆都很聰明並且掌握玩遊戲的最佳策略。編寫函數,給定石頭的個數,判斷你是否可以贏得遊戲。

例如,如果堆中有4顆石頭,那麼你一定不會贏得遊戲:無論你第一輪取走1,2,還是3顆石頭,下一輪你的朋友都可以取走餘下的所有石頭。

提示:

如果堆中有5顆石頭,你可以找出確保自己能贏的取石子策略嗎?

解題思路:

Nim遊戲的解題關鍵是尋找“必勝態”。

根據題設條件:

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

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

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

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

......

以此類推,可以得出結論:

當n % 4 != 0時,先手必勝;否則先手必負。

出處:http://bookshadow.com/weblog/2015/10/12/leetcode-nim-game/


代碼如下所示:

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


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