LeetCode:Nim Game - 尼姆博弈

1、题目名称

Nim Game(尼姆博弈)

2、题目地址

https://leetcode.com/problems/nim-game/

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.

中文:

你在和朋友玩“尼姆博弈”游戏,假设在桌上有一堆石子,二人轮流从这堆石子中拿走1到3块,取走最后一块石子的人获胜。这里假定你是第一个取石子的人。

假设你和你的对手都了解这个游戏的规则,写一个函数判定你是否可以取胜。

例如,如果有4块石头,那么你就是无法取胜的。无论你拿走1、2、3块石头,你的朋友都可以通过将其余的石子全部取走获胜。

4、解题方法1

网上已经有了很多对尼姆博弈问题的介绍,如维基百科页面:

https://en.wikipedia.org/wiki/Nim

解题Java代码如下:

/**
 * LeetCode 292 - Nim Game
 * @FileName Solution.java
 * @FileAuthor Tsybius
 * @DateTime 2015年12月20日 下午10:47:54
 */
public class Solution {
    
    /**
     * 计算尼姆博弈当前情况下是否必胜
     * @param n
     * @return
     */
    public boolean canWinNim(int n) {
        if (n <= 0) {
            return false;
        } else {
            return n % 4 != 0; 
        }
    }
}

另一种解法是讨论区大牛给出的方法,采用位运算解决本问题。

/**
 * LeetCode 292 - Nim Game
 * @FileName Solution.java
 * @FileAuthor Tsybius
 * @DateTime 2015年12月20日 下午10:54:12
 */
public class Solution {
    
    /**
     * 计算尼姆博弈当前情况下是否必胜
     * @param n
     * @return
     */
    public boolean canWinNim(int n) {
        if (n <= 0) {
            return false;
        } else {
            return n >> 2 << 2 != n;
        }
    }
}

END

转载于:https://my.oschina.net/Tsybius2014/blog/548232

博弈论 最近在刷挑战,做了博弈论专题,然后就成功的入了坑并且爬不上来了……所以今天想总结一下博弈论知识点+习题。 一、巴什博弈 只有一堆n个物品,两个人轮流从这堆物品中取物, 规定每次至少取一个,最多取m个。最后取光者得胜。(百度百科) 我们先考虑m=1的情况,即每人轮流取一个。这种情况下先手的必胜态:很显然就是n%2!=0。由特殊到一般,我们可以将这个公式推广:当m>1时,先手的必胜态:n%(m+1)!=0。 附上一道模板题:hdu1846 #include #include typedef long long ll; using namespace std; int C; int n, m; i 立即下载

相关推荐

解密 vn.py 源码:从事件驱动到模块化设计的实战解析

本文深入解析vn.py源码,重点剖析其事件驱动机制与模块化设计。通过事件引擎、处理器字典等核心组件分析,展示如何实现低耦合高内聚的交易系统架构,并结合实战案例说明模块化设计带来的开发效率提升。文章还详细解读了Gateway抽象层、核心数据结构及设计模式应用,为量化交易开发者提供源码级实践指南。

weixin_27427619的博客 257

Python聪明的尼姆游戏(人机对战)

Python聪明的尼姆游戏(人机对战)

WFQYYDS的博客 4285

量化投资从0开始系列 ---- 15. 郑商所日统计数据

前面已经提取了其它期货交易所的数据,最后还剩下郑商所。相比而言,郑商所的数据获取比其它几个交易所更麻烦一点。因为郑商所的系统接口有两个,在2015年11月11日前后发生了切换,这个日期之前是老系统的api接口,这个日期之后是一个新的api接口。 具体的地址在哪里,还是依靠在浏览器中按F12来确定,最后发现的地址是: if trade_date > '20151111': czce_url = f'http://www.czce.com.cn/cn/DFSS

kengxie的博客 2133

LeetCode 292. Nim 游戏【博弈论,脑筋急转弯】简单

You are playing the following Nim Game with your friend: Initially, there is a heap of stones on the table. You and your friend will alternate taking turns, and you go first. On each turn, the person whose turn it is will remove 1 to 3 stones from the hea

memcpy0的博客 596

BitLocker加密盘解密实战:从隐藏分区到密钥恢复的全过程

本文深入探讨了BitLocker加密盘在密钥丢失或遗忘情况下的解密实战方法。文章系统性地介绍了从理解加密机制、制作取证镜像,到深度扫描隐藏分区、分析内存转储寻找密钥残留,最终利用恢复密钥解锁加密卷的全过程。重点剖析了非标准恢复路径,为数据恢复和数字取证工作提供了专业的技术框架和实战思路。

weixin_29268385的博客 353

苏州大学自动化考研842自动控制原理:手把手教你用胡寿松《自控》高效备考(附复试电工/电子/微机原理攻略)

本文详细解析苏州大学自动化考研842自动控制原理备考策略,以胡寿松《自动控制原理》为核心教材,提供三阶段高效学习路径和实战技巧。重点涵盖频域分析、根轨迹绘制等高频考点,并针对机电、光电、轨道三个学院的复试科目(电工电子技术、电子技术基础、微机原理与接口技术)给出差异化备考方案,助力考生全面提升笔试和面试表现。

weixin_42638178的博客 414

题目7:编写程序,模拟尼姆游戏。

Python 尼姆游戏

m0_74373975的博客 1289

6.3 节深度拆解:Hermes Agent 多 Agent 协同执行链路的 4 层设计逻辑

拆解 Hermes 多 Agent 协同的 4 层工程化设计(协议层、编排层、执行层、适配层),聚焦协议层的强约束消息 Schema 如何解决 Agent 间语义不一致问题,并提供 `soul.md` 配置、GLM-4.7Flash 结构化输出验证及 v0.13.0/v0.14.0 版本实操避坑指南

weixin_42520239的博客 129

LeetCode从零单排之一分段——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 rem

yidaitian的专栏 988

基于Simulink的鲸鱼优化算法(WOA)MPPT仿真

摘要:本文介绍了基于Simulink的鲸鱼优化算法(WOA)在光伏MPPT控制中的应用。WOA模拟座头鲸的"气泡网捕食策略",通过包围猎物、螺旋收缩和随机搜索三阶段动态平衡全局探索与局部开发能力,有效解决局部阴影导致的多峰P-V曲线问题。文章详细讲解了WOA-MPPT的Simulink建模过程,包括多峰光伏阵列建模、WOA控制器实现和Boost变换器控制。仿真结果显示,在三种典型工况下,WOA-MPPT的追踪效率>99.3%,动态响应时间<0.15s,性能优于传统算法。最后提出了混合WO

amy_mhd的博客 78

淘宝滑块验证码破解:Python模拟鼠标轨迹过关详解

本文全面解析了淘宝滑块验证码的破解流程,从机制分析、图像处理、轨迹模拟到自动化实现,提供了完整的Python解决方案。随着2026年风控技术的升级,单纯依靠轨迹模拟已经难以达到高通过率,未来趋势是结合强化学习生成更自然的轨迹,并利用深度神经网络进行端到端的验证码绕过。此外,各大平台正逐步推广"无感验证"和"行为式验证码",将验证融入到用户正常操作中,这对爬虫技术提出了更高的挑战。技术本身是中立的,关键在于使用者的目的。希望本文能帮助开发者更好地理解验证码对抗技术,从而设计出更安全的防御系统。

2201_76125261的博客 101

2024年最全Python代码实现尼姆游戏聪明模式_尼姆游戏python代码,spring bean的生命周期面试题

Python崛起并且风靡,因为优点多、应用领域广、被大牛们认可。学习 Python 门槛很低,但它的晋级路线很多,通过它你能进入机器学习、数据挖掘、大数据,CS等更加高级的领域。Python可以做网络应用,可以做科学计算,数据分析,可以做网络爬虫,可以做机器学习、自然语言处理、可以写游戏、可以做桌面应用…Python可以做的很多,你需要学好基础,再选择明确的方向。这里给大家分享一份全套的 Python 学习资料,给那些想学习 Python 的小伙伴们一点帮助!

m0_54816834的博客 1022

跨平台CMake AutoSAR

AutoSAR是汽车行业采用的一种软件架构标准,它旨在提供一个通用的软件平台,使得汽车软件的开发和集成变得更加高效和灵活。总结一下,CMake AutoSAR是一个强大的跨平台工具,为AutoSAR开发提供了便利。通过简单的配置文件和命令,开发人员可以实现高效、灵活的跨平台开发,并加快自动驾驶系统的开发进程。上述示例中,我们定义了一个名为AutoSAR的项目,指定了源代码文件的路径和依赖库的路径。通过简单的配置文件和命令,开发人员可以实现高效、灵活的跨平台开发,并加快自动驾驶系统的开发进程。

EcmFsharp的博客 238

Leetcode 292 Nim Game

Leetcode 292 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...

qq_43271202的博客 293

jre9下载 jdk9

(Java SE Runtime Environment 9.0) 9.0u175 官方最新版 【x86|x64】

IDEA的使用指南

IDEA基于java的使用手册,可以最快速的上手,在使用中不断的丰富自己的使用技巧.

【LeetCode从零单刷】Nim Game

【LeetCode从零单刷】Nim Game

IronYoung_不惧未来 9536

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

[LeetCode]-292. Nim Game(Easy)(C + 尼姆游戏)

292. Nim Game    My Submissions Question Editorial Solution Total Accepted: 67907 Total Submissions: 128306 Difficulty: Easy You are playing the following Nim Game with your frien

保持对编程的热情! 1833

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

LeetCode 292. Nim Game

292. Nim Game 尼姆游戏 You are playing the following Nim Game with your friend: 您正在和您的朋友玩以下NIM游戏: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. 桌上有一堆石头,你...

Alex 652

LeetCode之Nim Game

1、题目 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 w

码莎拉蒂 2677

[Leetcode] 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

samjustin的博客 479

【Leetcode】292. Nim游戏

QUESTION easy 题目描述 你和你的朋友,两个人一起玩 Nim游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。 你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。 示例: 输入: 4 输出: false 解释: 如果堆中有 4 块石头,那么你永远不会赢得比赛; 因为无论你拿...

zzy0006的博客 235

LeetCode oj 292. Nim Game(尼姆博奕)

292. Nim Game   Question Editorial Solution  My Submissions Total Accepted: 100010Total Submissions: 184472Difficulty: Easy You are playing the following Nim Game with yo

Tristeza的博客 640

LeetCode(292) 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 th

指尖飞舞 2528

Nim游戏 Nim Game

https://leetcode.com/problems/nim-game/博弈论中极为经典的尼姆游戏。有总数为n的石头,每个人可以拿1~m个石头,两个人交替拿,拿到最后一个的人获胜。究竟是先手有利,还是后手有利?1个石子,先手全部拿走; 2个石子,先手全部拿走; 3个石子,先手全部拿走; 4个石子,后手面对的是先手的第1,2,3情况,后手必胜; 5个石子,先手拿走1个让后手面对第4种情况

知之可否 803
上一篇: LeetCode:Super Ugly Number - 超级丑数
下一篇: C# - 基于LinkLabel可动态生成多超链接信息的自定义控件
chenzai1946
博客等级 码龄10年 41粉丝 0原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值