2016.9.12; Leetcode 292. 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.

思路:這道題經過推演便可了解規律,推演過程如下:

石子數量 自己贏否(YES or NO) 理由
1 Y 簡單推演可得
2 Y 簡單推演可得
3 Y 簡單推演可得
4 N 簡單推演可得
5 Y 可以自己拿1個,剩下的4個,相當于對方先拿必輸,故我贏
6 Y 自己拿2個,剩4個,原理同石子數量為5
7 Y 自己拿3個,剩4個,原理同石子數量為6
8 N 不論自己拿1,2,3個,剩下5,6,7個,都相當于對方先拿,這樣對方贏,自己輸
9 Y 自己拿1個,剩下8個,相當于共有8個石子,對方先拿,對方必輸,我贏
10 Y 自己拿2個,剩下8個,相當于共有8個石子,對方先拿,對方必輸,我贏
11 Y 自己拿3個,剩下8個,相當于共有8個石子,對方先拿,對方必輸,我贏
12 N 不論自己拿1,2,3個,剩下11,10,9個,都相當于對方先拿,這樣對方贏,自己輸

故綜上所述,每當石子數量是4的倍數的時候,都是自己輸,否則自己必贏。

代碼如下

class Solution {
public:
    bool canWinNim(int n) {
        if(n%4 == 0){
            return false;
        }else{
            return true;
        }
    }
};
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容