Nim Game(leetcode)
来源:互联网 发布:美少女梦工厂4工作数据 编辑:程序博客网 时间:2024/06/08 02:30
Nim Game
- 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.
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.
解析
Nim Game的游戏规则为每人每次可以拿走1 - 3
块石头,胜者为拿走最后一块石头的人。
我们可以从中得到:假设有两个人A、B在玩Nim Game,A先拿,判断A是否能够获胜。
- 石头总数为
1
时,A拿走1
块石头,A取得胜利 - 石头总数为
2
时,A拿走2
块石头,A取得胜利 - 石头总数为
3
时,A拿走3
块石头,A取得胜利 - 石头总数为
4
时,无论A拿走多少块石头,A都无法取得胜利 (A->3, B->1; A->2, B->2; A->1, B->3) - 石头总数为
5
时,A先拿走1
块石头,无论B拿走多少块石头,最终都是A取得胜利 - 石头总数为
6
时,A先拿走2
块石头,无论B拿走多少块石头,最终都是A取得胜利 - 石头总数为
7
时,A先拿走3
块石头,无论B拿走多少块石头,最终都是A取得胜利
…………
观察上面可以知道,当剩余石头的块数是4的倍数的时候,需要拿石头的人游戏胜利无望。因此,想要在这个游戏中赢,必须使得当对手拿石头的时候,剩余的石头总数是4的倍数。
因此,一开始判断自己是否能在游戏中胜出,那么只需判断此时的石头总数是否为4的倍数。
解决
class Solution {public: bool canWinNim(int n) { if (n % 4 == 0) { return false; } else { return true; } }};
- Nim Game leetcode 292
- leetcode Nim Game
- [LeetCode 292] Nim Game
- leetcode | Nim Game
- leetcode 292---NIM GAME
- [leetcode] 292.Nim Game
- LeetCode:Nim Game
- leetcode-292-Nim Game
- LeetCode-Nim Game
- *LeetCode-Nim Game
- LeetCode Nim Game
- LeetCode之Nim Game
- 【Leetcode】Nim Game
- LeetCode 292----Nim Game
- LeetCode:Nim Game
- LeetCode -- Nim Game
- LeetCode--Nim Game
- [Leetcode] Nim Game
- 跟上 Java 8 – 你忽略了的新特性
- 推荐: Kafka详细原理总结
- 重写Collection.sort方法时,判断返回值作用
- java-MD5加密
- 折半插入排序
- Nim Game(leetcode)
- Spring+SpringMVC+MyBatis+easyUI整合基础篇(一)项目简述及技术选型介绍
- Kafka设计解析(一)- Kafka背景及架构介绍
- ElasticSearch入门 第四篇:使用C#添加和更新文档
- Python数据分析入门(一)-Pandas数据结构(Series)
- Python之创建数值列表
- java基础之集合(重点)
- AndroidStudio 2.2.3下配置Rxjava和Lamda表达式的开发环境
- jdbc交互数据库