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.
你和你的朋友一起玩下面的Nim游戲:在桌子上有一堆石頭,每次你輪流去除1到3塊石頭。 去除最后一塊石頭的人將是贏家。 你會采取第一個回合去除石頭。
你們都很聰明,并且有最好的策略。 編寫一個函數來確定是否可以贏得游戲給定的堆數量的石頭。
例如,如果在堆中有4塊石頭,那么你永遠不會贏得比賽:無論你刪除1,2,或3塊石頭,最后的石頭將永遠被你的朋友刪除。
暗示: 1.如果堆中有5塊石頭,你能找出一種方法去除石頭,讓你永遠是贏家嗎?
當題目告知4會死的時候就應該想到一定要把對手克制到4,想把對手克制到4,就要先把對手克制到8,,,即每逢4的倍數準會死
這個答案最簡單的。。
class Solution {public: bool canWinNim(int n) { return n%4!=0; }};相當于:bool canWinNim(int n) { if (n % 4 == 0) return false; else return true;}新聞熱點
疑難解答
圖片精選