題目描述:
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?
題目大意:
你正在和朋友玩下面的Nim游戲:桌子上有一堆石頭,每一次你們輪流取1至3顆石頭闹司。最后一個(gè)取走石頭的人就是贏家剥懒。第一輪由你先取。
你們倆都很聰明并且掌握玩游戲的最佳策略匿乃。編寫函數(shù)桩皿,給定石頭的個(gè)數(shù),判斷你是否可以贏得游戲幢炸。
例如泄隔,如果堆中有4顆石頭,那么你一定不會(huì)贏得游戲:無論你第一輪取走1阳懂,2梅尤,還是3顆石頭,下一輪你的朋友都可以取走余下的所有石頭岩调。
提示:
如果堆中有5顆石頭巷燥,你可以找出確保自己能贏的取石子策略嗎?
解題思路:
當(dāng)n∈[1,3]時(shí)号枕,先手必勝缰揪。
當(dāng)n==4時(shí),無論第一輪取得1至3中幾顆石頭,都會(huì)導(dǎo)致第二輪重復(fù)n∈[1,3]的情況钝腺,所以此時(shí)必負(fù)抛姑。
當(dāng)n∈[5,7]時(shí),通過分別取走[1,3]顆石頭艳狐,使第二輪情況轉(zhuǎn)化為n==4定硝,此時(shí)先手必勝,后手必負(fù)毫目。
當(dāng)n==8時(shí)蔬啡,無論第一輪取得1至3中幾顆石頭,都會(huì)導(dǎo)致第二輪重復(fù)n∈[5,7]的情況镀虐,所以此時(shí)先手必負(fù)箱蟆。
...
可得出結(jié)論:
當(dāng) n%4 !=0 時(shí),先手必勝刮便;否則先手必負(fù)空猜。
C++代碼:
class Solution {
? ? public:
? ? ? ? bool canWinNim(int n) {
? ? ? ? return n % 4 != 0;
? ? ? ? }
};