博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 292 Nim Game(Nim游戏)
阅读量:7041 次
发布时间:2019-06-28

本文共 1430 字,大约阅读时间需要 4 分钟。

翻译

你正在和你的朋友们玩以下这个Nim游戏:桌子上有一堆石头。每次你从中去掉1-3个。谁消除掉最后一个石头即为赢家。你在取出石头的第一轮。你们中的每个人都有着聪明的头脑和绝佳的策略。写一个函数来确定对于给定的数字是否你能够赢得这场比赛。比如,假设堆中有4个石头,那么你永远也无法赢得比赛:不管你移除了1、2或3个石头,最后一个石头都会被你的朋友所移除。

原文

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.

分析

题目一開始不是非常理解,由于朋友假设有2个、3个、多个的情况是全然不一样的呐,后来细致一看原文第一句withyourfriend,发现仅仅是和1个朋友玩游戏。

于是我设定了一个推断条件

bool yourTrun = true;

后面巴拉巴拉写了一堆代码全错……

加上一天的劳苦我開始趴着睡觉了,脑子里还在回忆。忽然发现:

1-true2-true3-true4-false5-true6-true7-true8-false

然后抬起头又一次写了一遍:

bool canWinNim(int n) {    if ((n - 1) % 4 == 0 || (n - 2) % 4 == 0 || (n - 3) % 4== 0) return true;           else return false;             }

哇。通过了,感觉整理整理:

bool canWinNim(int n) {    return (n - 1) % 4 == 0 || (n - 2) % 4 == 0 || (n - 3) % 4 == 0;}

继续整理。原来这么简单呐:

bool canWinNim(int n) {    return n % 4 != 0;}

忽然就不困了。

^_^

代码

class Solution {public:          bool canWinNim(int n) {        return n % 4 != 0;    }};

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

你可能感兴趣的文章
云计算与网格计算的深入比较
查看>>
Mybatis oracle多表联合查询分页数据重复的问题
查看>>
oc83--自定义类实现copy方法
查看>>
What's New in iOS7,iOS7新特性介绍
查看>>
电源管理里的休眠选项卡没了
查看>>
Xshell高级后门完整分析报告
查看>>
sphinx是支持结果聚类的
查看>>
PL/SQLDeveloper导入导出Oracle数据库方法
查看>>
救人一命是怎样的体验?
查看>>
php如何妩媚地生成执行的sql语句
查看>>
搜索引擎收录提交入口
查看>>
MongoDB简单实践:Only CRUD
查看>>
C语言杂谈——预处理程序
查看>>
如何从TFS中删除团队项目
查看>>
C++中的指针与引用
查看>>
Visual Studio 2017 15.5.0 正式发布 正式版下载
查看>>
2.2 Consumer API官网剖析(博主推荐)
查看>>
[转]js日期时间函数(经典+完善+实用)
查看>>
Visual Studio 2008中 显示解决方案管理器中的解决方案节点,VS 2010 高级专业版 序列号...
查看>>
SharePoint Framework 构建你的第一个web部件(一)
查看>>