[LeetCode] 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.

Hint:

  1. If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner?

Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

 

有史以來最少代碼量的解法,雖然解法很簡單,但是題目還是蠻有意思的,題目說給我們一堆石子,每次可以拿一個兩個或三個,兩個人輪流拿,拿到最后一個石子的人獲勝,現在給我們一堆石子的個數,問我們能不能贏。那么我們就從最開始分析,由於是我們先拿,那么3個以內(包括3個)的石子,我們直接贏,如果共4個,那么我們一定輸,因為不管我們取幾個,下一個人一次都能取完。如果共5個,我們贏,因為我們可以取一個,然后變成4個讓別人取,根據上面的分析我們贏,所以我們列出1到10個的情況如下:

1    Win

2    Win

3    Win

4    Lost

5    Win

6    Win

7    Win

8    Lost

9    Win

10   Win

由此我們可以發現規律,只要是4的倍數個,我們一定會輸,所以對4取余即可,參見代碼如下:

 

class Solution {
public:
    bool canWinNim(int n) {
        return n % 4;
    }
};

 

討論:我們來generalize一下這道題,當可以拿1~n個石子時,那么個數為(n+1)的整數倍時一定會輸,我們試着證明一下這個結論,若當前共有m*(n+1)個石子,那么:

當m=1時,即剩n+1個的時候,肯定會輸,因為不管你取1~n中的任何一個數字,另一個人都可以取完。
當m>1時,即有m*(n+1)的時候,不管你先取1~n中的任何一個數字x,另外一個人一定會取n+1-x個,這樣總數就變成了(m-1)*(n+1),第二個人就一直按這個策略取,那么直到剩n+1個的時候,就便變成m=1的情況,一定會輸。

 

類似題目:

Flip Game II

 

參考資料:

https://leetcode.com/problems/nim-game/solution/

https://leetcode.com/problems/nim-game/discuss/73749/Theorem:-all-4s-shall-be-false

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM