您的位置:首页 > 其它

【一天一道LeetCode】#292. Nim Game

2016-07-09 21:29 288 查看

一天一道LeetCode

从今天开始,调整规律,不按顺序做,从easy开始!


本系列文章已全部上传至我的github,地址:ZeeCoder‘s Github

欢迎大家关注我的新浪微博,我的新浪微博

欢迎转载,转载请注明出处



(一)题目


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.

Hint:

1. 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?



(二)解题

题目大意:nim游戏,游戏的规则是:桌上有一堆石头,数量为n,你和你的朋友每次从里面拿1~3个石头,谁最后一个拿完谁就赢了。

初次看到这题,真是一点思路都没有,不过,突然想起来在牛客网上刷过这题,【面试笔试算法】牛客网一站通Offer编程题2016.4.19

印象中是到找规律的题,于是开始一个一个找规律。

1--true
2--true
3--true
4--false
5--true
6--true
7--true
8--false


于是,这道题一句话就能解决了。哈哈,看到AC的那一刻,真是觉得,题目吓人,一大堆,讲的云里雾里,结果一句话就摆平了!!

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