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.

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.

解析

題目大意還是比較好理解的,下面稍微擴(kuò)展一下:
假設(shè)一堆里面有n個(gè)石頭,每次可以取1-m個(gè)石頭。
(1)若n=m+1,則先取者無論取多少石頭,后取者都可以拿走所有的石頭。先取者必輸;
(2)若n=k(m+1),若先取者先取k(1<k<m)個(gè)石頭,則后取者取m+1-k個(gè)石頭就達(dá)到平衡,這樣先取者也必輸;
(3)若n=k(m+1)+s,那么先取者先取s(s>1 && s%(m+1)!=0)個(gè)石頭后n為k(m+1),回到了第二種情況,就轉(zhuǎn)化為第二個(gè)人先取,這樣第一個(gè)人必贏。
因此代碼就很容易了。

代碼(C語言)

bool canWinNim(int n) {
    return n % 4 ? true : false;
}

有興趣的老鐵可以擴(kuò)展解決一下Nim Game原型,Nim博弈。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容