Nim Game -- leetcode

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.

Hint:

  1. If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

這道題更像是一個腦筋急轉換的題。

如果按常理,寫一個遞歸,必定會遇到棧溢出的問題。


然而當分析,每一輪保證去掉4個時,你就能清楚的知道是否會獲勝。

當對手拿掉1個,你拿掉3個;

   對手拿掉2個,你拿掉2個;

   對手拿掉3個,你拿掉1個。


當stones的個數被4整除,所得餘數。爲1,2,3時,你先手拿掉這些零頭,那麼剩下的stones數量爲4的倍數。然後,勝利就在你的撐握中。

然而,當stones的個數剛好被4整除時。由於你爲先手,形勢反轉爲對手就能剛剛好掌握住勝利。


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






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