• 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. 拓展

  • 相关阅读:
    378. Kth Smallest Element in a Sorted Matrix
    372. Super Pow
    357. Count Numbers with Unique Digits
    345. Reverse Vowels of a String
    343. Integer Break
    347. Top K Frequent Elements
    344. Reverse String
    338. Counting Bits
    326. Power of Three
    python练习
  • 原文地址:https://www.cnblogs.com/whl2012/p/5596610.html
Copyright © 2020-2023  润新知