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:
- 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)個石子,那么:
類似題目:
參考資料:
https://leetcode.com/problems/nim-game/solution/
https://leetcode.com/problems/nim-game/discuss/73749/Theorem:-all-4s-shall-be-false