letecode [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.
Example:
Input: 4
Output: false
Explanation: 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.
题目大意:
你和你的朋友,两个人一起玩 Nim 游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。
你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
理 解:
观察示例,当n = 4时,先手输。当n = 1\2\3时, 先手赢。
当n = 5/6/7时,先手可以拿1/2/3使得 对手的n为4,则先手赢。
当n = 8时,先手拿1\2\3个,对手都能将剩余的石头个数变为4,则先手输。
观察规律,可发现,当n 为4 的倍数时,先手输,反之先手赢。
代 码 C++:
class Solution { public: bool canWinNim(int n) { if(n<=0) return false; return !(n%4==0); } };
运行结果:
执行用时 :0 ms, 在所有C++提交中击败了100.00%的用户
内存消耗 :8.2 MB, 在所有C++提交中击败了5.69%的用户