zoukankan      html  css  js  c++  java
  • 292. 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 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:
    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?
    Tags: Brainteaser
    Similar Problems: (M) Flip Game II

    2. 解题思路

    刚看这个题目时毫无头绪,而LeetCode将其列为Easy,故静下心来进行分析

    • 当n<=3时,先手必胜
    • 当n = 4时,先手必败,后手必胜
    • 当n = 5时,先手可选方案为:

    题目中说Both of you are very clever and have optimal strategies for the game,故n=5时,先手必选方案1。

    • 当n = 6时,先手可选方案为:

    ,故n=6时,先手必选方案2。

    • 以此类推,可知只有当出现了4的倍数,先手无可奈何,其余情况先手都可以获胜。 (石子数量为4的倍数)

    3. 代码

    class Solution {
    public:
        bool canWinNim(int n)
        {
            n = n%4;
            if (0 == n)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    };

    4. 反思

    • 举一反三:面对毫无头绪的问题时,从最简单的情况开始分析,往往能够发现规律!
    • 查资料发现:这是博弈论中极为经典的尼姆游戏。有总数为n的石头,每个人可以拿1~m个石头,两个人交替拿,拿到最后一个的人获胜。究竟是先手有利,还是后手有利?
    • 规律:
      • 先手的获胜策略:每次都令取之后剩余的石子数量为4的倍数(4*0=0,直接拿光)
      • 后手的获胜策略:先手必会使剩余的石子数量为4的倍数,故后手每次取石子的数量,与上一次先手取石子的数量和为4即可,此时剩余石子数量必不为4的倍数

    • 此题是Nim Game的最简单的一种情况,获胜:堆中元素数目不能整除4;失败:堆中元素数目能整除4。

    5. 拓展

  • 相关阅读:
    php数组的使用
    php数组的定义、php数组的类型
    小米手机安卓手机微信里出现意外的边框线,border:0也没用
    php实现WEB在线文件管理器
    安装了https ssl证书,但浏览器显示并非完全安全(此页面内容部分不安全)
    thinkphp无限分类模块实现
    常见的移动web问题,终端触摸交互,各种bug坑如何解决
    现代都市风 移动端可折叠导航菜单
    电器类电商网站分类大菜单,配色超舒服~
    帮助中心模板框架--简约小清新风格
  • 原文地址:https://www.cnblogs.com/whl2012/p/5596610.html
Copyright © 2011-2022 走看看