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.

思路

純數學題,這種題目一般找規律用數學歸納法

  • stones = 1: 拿一個,必贏
  • stones = 2: 拿兩個,必贏
  • stones = 3: 拿三個,必贏
  • stones = 4: 不管拿幾個,必輸
  • stones = 5: 拿一個,必贏
  • stones = 6: 拿兩個,必贏
  • stones = 7: 拿三個,必贏
  • stones = 8: 不管拿幾個,必輸
  • ...........

由此可見 當 stones 是 4 的倍數是必輸

bool canWinNim(int n) {
    
    return n % 4;  // 無需考慮負數的情況,這個應該是調用者自己負責
    
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容