292. Nim Game
来源:互联网 发布:淘客cms微信系统 编辑:程序博客网 时间:2024/06/04 01:14
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.
假设还有n个石头,而且玩家B最后拿,那么玩家B可以拿的石头是1,2,3个,玩家A可以拿的情况有以下9种:B (x-1) -> A: (x-2), (x-3), (x-4)B (x-2) -> A: (x-3), (x-4), (x-5)B (x-3) -> A: (x-4), (x-5), (x-6)
那么f(x)的状态就是:
f(x) = (f(x-2)&&f(x-3)&&f(x-4)) || (f(x-3)&&f(x-4)&&f(x-5)) || (f(x-4)&&f(x-5)&&f(x-6))这里可以发现,如果f(x-4)是false,那么B就不会赢。
初始条件n=1,2,3时,A都可以赢,4时A必输。按照上面的想法,n=5,6,7时,A可以赢,8时A必输。所以代码如下:
public class Solution { public boolean canWinNim(int n) { return (n % 4 != 0); }}
0 0
- [leetcode] 292.Nim Game
- 【LeetCode】292.Nim Game
- 292. Nim Game
- leetcode:292. Nim Game
- 292. Nim Game
- 292. Nim Game
- 292. Nim Game
- leetCode 292. Nim Game
- 292. Nim Game LeetCode
- 292. Nim Game
- LeetCode 292. Nim Game
- LeetCode 292. Nim Game
- LeetCode 292.Nim Game
- LeetCode 292. Nim Game
- 292. Nim Game
- 292. Nim Game
- 292. Nim Game
- 292. Nim Game
- 资源加载操作_FindResource_LoadResource_LockResource
- 应用层 加载驱动 和 卸载驱动代码
- Fix for Debug Assertion Failed! Expression: __acrt_first_block == header
- 【Video】音视频领域知识
- Codeforces 699 C. Vacations ( 贪心
- 292. Nim Game
- 用户层加载驱动 卸载驱动源码
- Flume 1.6 遇Emoji表情发生截断丢失数据问题分析
- 开源项目Meizhi学习笔记--工具类的收集
- 任意数据长度的bitset,以及按位读写数据的函数
- 像写文章一样使用 Kotlin
- c++ 字符串分割函数stringsplit
- 235. Lowest Common Ancestor of a Binary Search Tree
- 文件名匹配查找