LeetCode:Nim Game
2015-10-29 00:32
218 查看
问题描述:
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:
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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
思路:
写出能够win的情况,找到规律,居然都是4的倍数,所以代码就很简单了。
代码:
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:
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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
思路:
写出能够win的情况,找到规律,居然都是4的倍数,所以代码就很简单了。
代码:
<pre name="code" class="cpp">class Solution { public: bool canWinNim(int n) { if(n > 0 && n < 4) return true; if(n % 4 == 0) return false; else return true; } };
相关文章推荐
- MyEclipse(Eclipse)安装后需要进行的配置
- 安装解压版MySQL5.6
- [LeetCode] Product of Array Except Self
- Volley 加载图片,文件缓存
- Search a 2D Matrix II
- POJ 3186 Treats for the Cows
- RCU synchronize原理分析
- POJ 3186 Treats for the Cows
- basename函数使用
- laravel ajax表格删除
- Centos查看端口占用情况和开启端口命令
- ecshop 突然运行很慢的原因 ecshop数据库ecs_stats总是很大的解决方法
- Objective-C语法之动态类型(isKindOfClass, isMemberOfClass,id)等
- Excel Sheet Column Number
- 指针学习笔记(3)——小结
- kali——google安装
- 如果我来应聘产品经理岗位(二)
- python多线程threading
- How the performance impacts your revenue-性能影响营收
- iOS学习之UINavigationController详解与使用(三)ToolBar