博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
292. Nim Game
阅读量:6837 次
发布时间:2019-06-26

本文共 1368 字,大约阅读时间需要 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:

  1. 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?

链接: 

题解:

看来我的推测是对的。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

 

转载地址:http://hhqkl.baihongyu.com/

你可能感兴趣的文章
Centos 安装 Solr
查看>>
Android Toast自己定义Toast例子
查看>>
bash shell实现二进制与十进制数的互转
查看>>
精准测试
查看>>
Oracle11G_逻辑备份
查看>>
Linux正变得无处不在;应用大盘点
查看>>
IEEE期刊
查看>>
pssh使用
查看>>
索引优化系列十四--啥时分区索引性能反而低
查看>>
hive的变量传递设置
查看>>
apache-shiro杂记(三) 用了apache-shiro后,HttpSession.getServletContext() API无法正常工作了...
查看>>
Jquery的$命名冲突
查看>>
经常用到的JS 表单验证函数
查看>>
eclipse 中的 maven run configurations
查看>>
并查集
查看>>
无刷新读取数据库 (ajax)
查看>>
mysql事务介绍
查看>>
css(hr元素)水平线的定位
查看>>
Cisco路由交换--NAT详解一
查看>>
1.7Discuz_X3.2论坛软件搭建
查看>>