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

    题目:

    你和你的好基友在玩一个叫Nim的游戏:桌子上有一堆小石子,你或你基友轮流从中拿出1到3颗小石子。能拿完最后剩下的所有小石子的人获胜。你先开始拿。

    假设:你和你基友都是IQ非常高的人,而且都是玩这个游戏的老手(深谙玩这个游戏的套路)。

    你能否写个函数,用来计算对给定数目的小石子,你是否能赢下比赛。

    eg:如果有4个小石子,你肯定会输的,因为不管你拿走1个、2个还是3个,最后剩下的小石子都会被你好基友拿完。

    分析:如果轮到你拿的时候,剩下4个小石子,你就悲剧了。

        同理,如果你拿的时候还剩下8个小石子,不管你选择拿1个、2个还是3个,你朋友都能让你下次拿的时候剩下4个。

        递推地:假设在轮到你你拿的时候还剩4*n个小石子,不管你选择拿1个、2个还是3个,你朋友都能让你下次拿的时候还剩4*(n-1)个;

        也就是,你朋友可以让你每次拿之前,都剩4n个小石子;(n为大于等于1的正整数);这样递推下去,最后你就输了。

    1 public class Solution {
    2     public boolean canWinNim(int n) {
    3         return n % 4 == 0;
    4     }
    5 }

        

  • 相关阅读:
    《免费:商业的未来》书摘
    wxWidgets的安装编译、相关配置、问题分析处理
    CodeBlocks的下载安装、配置、简单编程
    【最新】让快捷方式 实现相对路径——非.bat方式实现
    跨平台C/C++集成开发环境-Code::Blocks-内置GCC
    IOS自定义alertview
    IOS快速开发之常量定义
    为UITableViewController瘦身
    IOS中扩展机制Category和associative
    IOS制作一个漂亮的登录界面
  • 原文地址:https://www.cnblogs.com/HITSZ/p/6613692.html
Copyright © 2011-2022 走看看