[LeetCode] NO.292 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.
[題目解析]: 根據(jù)題目進(jìn)行分析,當(dāng)有4個(gè)石頭的時(shí)候,無(wú)論你拿1,2還是3個(gè),對(duì)手都可以最后一個(gè)拿完,你永遠(yuǎn)不會(huì)贏。
? ? ? ? 依次類(lèi)推,當(dāng)有5個(gè)石頭的時(shí)候,你拿1個(gè),留給對(duì)方4個(gè),對(duì)方必輸;當(dāng)有6個(gè)石頭的時(shí)候,你拿2個(gè),對(duì)方必輸;當(dāng)有7個(gè)石頭的時(shí)候,你拿3個(gè),對(duì)方必輸。而當(dāng)有8個(gè)石頭的時(shí)候,你無(wú)論拿1,2,還是3個(gè),都留給對(duì)方7,6,5三種,對(duì)方都必贏。繼續(xù)類(lèi)推呢,發(fā)現(xiàn)規(guī)律了嗎?n%4等于0的時(shí)候,你必輸,其他情況你都可以贏。
? ? ? ??
public boolean canWinNim(int n) {if(n <= 0) return false;return !(n%4 == 0);}?
轉(zhuǎn)載于:https://www.cnblogs.com/zzchit/p/5767704.html
總結(jié)
以上是生活随笔為你收集整理的[LeetCode] NO.292 Nim Game的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 50首关于月亮的古诗短篇
- 下一篇: 第二周作业内容: