LeetCode OJ 之 Nim Game(翻摊游戏)
来源:互联网 发布:软件测试招聘上海 编辑:程序博客网 时间:2024/05/13 21:31
题目:
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?
思路:
如果给定的数字n是4的倍数,那么先取者必输。假设先取者每次拿x个石头,后取者只要拿4-x个石头,那么最后一次一定是后取者拿到。比如8,无论先取者第一次拿1,2,3,只要后取者拿4-x个,就回到了题目给的4个石头的情况,这样后取者必赢。
如果给定的数字不是4的倍数,那么先取者必赢。需要先取者首次拿n%4个石头。假设后取者每次拿y个石头,先取者在他下次只要拿4-y个石头,那么最后一次一定是先取者拿到。比如9,先取者第一次拿一个石头就变成了上面的情况。
因此只需判断所给数字是否是4的倍数即可。
代码:
class Solution {public: bool canWinNim(int n) { return n % 4; }};
- LeetCode OJ 之 Nim Game(翻摊游戏)
- LeetCode 292 Nim Game(Nim游戏)
- LeetCode oj 292. Nim Game(尼姆博奕)
- <LeetCode OJ> 292. Nim Game
- LeetCode OJ-292. Nim Game
- LeetCode之Nim Game
- LeetCode之 Nim Game
- Leetcode之Nim Game
- leetcode 之Nim Game
- LeetCode之Nim Game
- LeetCode 292: Nim Game (Nim游戏)
- LeetCode OJ 之 Jump Game (“跳跃”游戏 - 一)
- LeetCode OJ 之 Jump Game II(“跳跃”游戏 - 二)
- LeetCode 292. Nim Game(取物游戏)
- Nim游戏 Nim Game
- leetcode 292. Nim Game(拿石子游戏)
- 【LeetCode】001 Nim Game 尼姆游戏
- [Leetcode] Nim Game 尼姆游戏
- 八大排序算法
- WPF导学目录
- 动态规划算法
- 浅谈企业应用软件架构设计过程
- UIView常用的一些方法小记之setNeedsDisplay和setNeedsLayout
- LeetCode OJ 之 Nim Game(翻摊游戏)
- Dijkstra算法(单源最短路径)
- 看完20部电影,你可以去任何一家公司做董事长或总经理
- Masonry 自动布局 cocopods
- 编程养成了思考习惯
- hibernate读写对象类型
- Spring <context:annotation-config/> 解说
- 阿里云解决wordpress无法建立目录 uploads/年/月份。有没有上级目录的写权限?
- DataSet与DataType