1. 程式人生 > >LeetCode-Nim Game

LeetCode-Nim Game

Description: 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.

題意:有一堆一定數量的石頭,雙方每次可以輪流區1-3顆,哪一方先取到最後一顆石頭,哪一方獲勝;現在要求計算,當你是先手時是否可以勝利;

解法:Nim是博弈論中的經典問題;對於這道題目來說,我們記石頭的數量為n;

  • 如果n <= 3,那麼我們一定可以獲勝
  • 如果n == 4,那麼無論我們取1, 2或者3顆都無法獲勝;因此,為了保證我們可以獲勝,需要避免當輪到我們取時石頭數量為4
  • 同理,當n=[5,6,7]時,我們可以獲勝
  • 如果n == 8,無論我們取1,2或者3顆,都無法確保當下次輪到我們時石頭數量為4

綜上所述,我們只需要判斷石頭的數量是否為4的倍數即可知道能否獲勝;

Java
class Solution {
    public boolean canWinNim(int n) {
        return n % 4 == 0 ? false : true;
    }
}