您的位置:首页 > 其它

292. Nim Game

2016-05-13 13:02 295 查看

292. Nim Game

Description:

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.

Example:

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?

Link:

https://leetcode.com/problems/nim-game/

Analysis:

1.对于Nim Game不了解的可先自行百度一下。

2.面对这种问题可以先在纸上尝试一些数,找一下规律。(W:赢,L:输)

12345678910111213141516171819
WWWLWWWLWWWLWWWLWWW
3.尝试过后,我们至少可以发现两点规律。

A. 每当是四的倍数的时候会输。

B. 每次你的输赢只取决于前三次的输赢,比如:当有8个stones时,分别看第7、6、5次的输赢,如果前三次均为W,那你这次肯定输了。因为你只能pick 1、2、3个stones,所以对方肯定是赢的。

4.综上,至少有两种方法:一种是判断是否为4的整数倍;另一种当然是用递归看前三次的输赢啦。

Source Code(C++):

#include <iostream>
#include <vector>
using namespace std;

/****************************方法1:使用递归来解决************************************************/
/*
class Solution {
public:
bool canWinNim(int n) {
if (n==1 || n==2 || n==3) {
return true;
}
if (canWinNim(n-1)==false || canWinNim(n-2)==false || canWinNim(n-3)==false) {
return true;
}
else {
return false;
}
}
};
*/
/**********************方法2:使用递推实现递归来解决问题***************************************/
/*
class Solution {
public:
bool canWinNim(int n) {
vector<bool> v(n, true);
for (int i=3; i < v.size(); i++) {
if (v.at(i-1)==false || v.at(i-2)==false || v.at(i-3)==false) {
v.at(i) = true;
}
else {
v.at(i) = false;
}
}
return v.at(n-1);
}
};
*/
/*********************************方法3:观察规律得只有在4的整数倍时会输************************/
class Solution {
public:
bool canWinNim(int n) {
return n%4!=0;
}
};

int main()
{
Solution s;
cout << s.canWinNim(40);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: