題目
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博弈。