292. Nim Game
2015-12-13 07:36
246 查看
题目:
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?
链接: http://leetcode.com/problems/nim-game/
题解:
看来我的推测是对的。jianchao.li真的加了很多很多数学有关的趣题...这个也是很有意思,第一次接触是在小时候看古畑任三郎第一季最后一集里老爷和数学家(毛利小五郎)对弈,玩的就是这个游戏。关键就是4的倍数一定是false,所以我们直接返回结果。
二刷:
Java:
Time Complexity - O(1), Space Complexity - O(1)
三刷:
Java:
Reference:
https://leetcode.com/discuss/63725/theorem-all-4s-shall-be-false https://leetcode.com/discuss/63978/one-line-o-1-solution-and-explanation
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?
链接: http://leetcode.com/problems/nim-game/
题解:
看来我的推测是对的。jianchao.li真的加了很多很多数学有关的趣题...这个也是很有意思,第一次接触是在小时候看古畑任三郎第一季最后一集里老爷和数学家(毛利小五郎)对弈,玩的就是这个游戏。关键就是4的倍数一定是false,所以我们直接返回结果。
public class Solution { public boolean canWinNim(int n) { return n % 4 != 0; } }
二刷:
Java:
Time Complexity - O(1), Space Complexity - O(1)
public class Solution { public boolean canWinNim(int n) { return n % 4 != 0; } }
三刷:
Java:
public class Solution { public boolean canWinNim(int n) { return n % 4 != 0; } }
Reference:
https://leetcode.com/discuss/63725/theorem-all-4s-shall-be-false https://leetcode.com/discuss/63978/one-line-o-1-solution-and-explanation
相关文章推荐
- Java菜鸟入门(20) Producer Consumer经典代码
- 揭秘中国四大最顶级圈子,他们手里几乎握着整个民营经济的钱
- jpa使用记录
- 泛型的内部原理:类型擦除以及类型擦除带来的问题
- activity生命周期完整版
- 发送手机物理标识请求
- 框架和类库的区别
- 上传Apk至测试服务器
- 计步器算法简述和模块使用
- 创建动态链接库时设置导出函数的方法
- java框架
- [leetcode] 131. Palindrome Partitioning 解题报告
- 291. Word Pattern II
- Codeforces 602B
- 查看动态链接库中函数参数类型
- 【转】JDK工具jinfo用法详解
- VS2010 + QT5.2+ QT-VS-Addin1.2.2开发环境配置
- [MetaHook] Event Hook
- 蓝桥杯预选反思
- BugPhobia开发篇章:Beta阶段第I次Scrum Meeting