zoukankan      html  css  js  c++  java
  • 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 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.

    Example:

    Input: 4
    Output: false 
    Explanation: 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,2,3个石头,最后一个拿走石头的人获胜。

    那么我们可以对最基本的情况进行分析:

      当剩余0个石头时,都被对方拿走了:失败

      当剩余1个石头时,可以全拿走:胜利

      当剩余2个石头时,可以全拿走:胜利

      当剩余3个石头时,可以全拿走:胜利

      当剩余4个石头时,拿多少剩下的都会被全拿走(因为你和你的对手都足够聪明):失败

      

      当有其他数目的石头时,你可以想尽办法给你的对手留下4个石头,同样的你的对手由于足够聪明也会想尽办法留下4个石头给你。

    代码:

    class Solution {
    public:
        bool canWinNim(int n) {
            return n%4;
        }
    };
  • 相关阅读:
    Java 将Clob字段转换成String字符串
    Java BigDecimal详解
    java循环创建对象应该在循环体内还是循环体外
    Java 通过身份证获取生日和性别
    Java将数据进行分组处理
    Java 2进制和16进制的转换
    Map-HashMap 与 IF 判断内存占用对比
    Groovy脚本-通用SQL开关
    Oracle用户、授权、角色管理
    【docker随笔系列】安装sqlserver
  • 原文地址:https://www.cnblogs.com/yaoyudadudu/p/9216138.html
Copyright © 2011-2022 走看看