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遊戲的解題關鍵是尋找“必勝態”。
根據題設條件:
......
以此類推,可以得出結論:
出處:http://bookshadow.com/weblog/2015/10/12/leetcode-nim-game/
class Solution {
public:
bool canWinNim(int n)
{
return n % 4 != 0;
}
};