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.
class Solution {
public:
bool canWinNim(int n)
{
if (n <= 3) return true;
for (int i = 1; i <= 3; i++)
{
if (!canWinNim(n - i)) //B如果在一种情况下肯定输,那A肯定能赢
return true;
}
return false;
}
};
class Solution {
public:
bool canWinNim(int n)
{
if (n <= 3) return true;
vector<bool> canwin(n + 1, false);
for (int k = 1; k <= 3; k++) canwin[k] = true;
for (int i = 4; i <= n; i++)
{
for (int k = 1; k <= 3; k++)
{
if (!canwin[i - k]) //A取了之后B有一种情况肯定输,那A肯定赢
{
canwin[i] = true;
break;
}
}
}
return canwin[n];
}
};那就只能找规律了 :)
class Solution {
public:
bool canWinNim(int n)
{
return n % 4;
}
};
本文探讨了一种名为Nim的游戏,玩家轮流从一堆石头中移除1到3个石头,拿走最后一个石头的人获胜。文章提供了几种解决方案,包括递归方法、使用数组的方法,并最终发现了一个简单的规律来判断玩家是否能够赢得游戏。
417

被折叠的 条评论
为什么被折叠?



