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īng)過推演便可了解規(guī)律,推演過程如下:
石子數(shù)量 | 自己贏否(YES or NO) | 理由 |
---|---|---|
1 | Y | 簡(jiǎn)單推演可得 |
2 | Y | 簡(jiǎn)單推演可得 |
3 | Y | 簡(jiǎn)單推演可得 |
4 | N | 簡(jiǎn)單推演可得 |
5 | Y | 可以自己拿1個(gè),剩下的4個(gè),相當(dāng)于對(duì)方先拿必輸,故我贏 |
6 | Y | 自己拿2個(gè),剩4個(gè),原理同石子數(shù)量為5 |
7 | Y | 自己拿3個(gè),剩4個(gè),原理同石子數(shù)量為6 |
8 | N | 不論自己拿1,2,3個(gè),剩下5,6,7個(gè),都相當(dāng)于對(duì)方先拿,這樣對(duì)方贏,自己輸 |
9 | Y | 自己拿1個(gè),剩下8個(gè),相當(dāng)于共有8個(gè)石子,對(duì)方先拿,對(duì)方必輸,我贏 |
10 | Y | 自己拿2個(gè),剩下8個(gè),相當(dāng)于共有8個(gè)石子,對(duì)方先拿,對(duì)方必輸,我贏 |
11 | Y | 自己拿3個(gè),剩下8個(gè),相當(dāng)于共有8個(gè)石子,對(duì)方先拿,對(duì)方必輸,我贏 |
12 | N | 不論自己拿1,2,3個(gè),剩下11,10,9個(gè),都相當(dāng)于對(duì)方先拿,這樣對(duì)方贏,自己輸 |
故綜上所述,每當(dāng)石子數(shù)量是4的倍數(shù)的時(shí)候,都是自己輸,否則自己必贏。
代碼如下
class Solution {
public:
bool canWinNim(int n) {
if(n%4 == 0){
return false;
}else{
return true;
}
}
};