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.


    题目标签:Brainteaser

      这道题目给我们一个数字,代表是石头的数量,让我们判断,能赢还是没机会赢,这里假设两个玩家都是有最精确的策略。还有就是,游戏里我是先走的那个,而且每个人一次只能取1或者2或者3个石头。

      那我们来举例子看一下:

           n  我

      1  win

      2  win

      3  win

      4  lose

      5  win

      6  win

      7  win

      8  lose

      9  win

      10  win

      11  win

      12  lose

      我们看到,只有在4的倍数的情况下,我们会输。来分析一下,当给的数字是4的倍数时候,无论我们怎么拿,拿1,2,3。对方都能够化解,然后返回给我们一个4的倍数,这里的策略就是,谁能给对方留下一个4的倍数,就一定能赢。换一句话说,就是谁拿到4的倍数一定会输(除非对方失误)。在不是拿到4的倍数的情况下,只要每一次留给对方4的倍数,我们就可以一直保持到倒数第三轮,给对方4, 对方无论拿走1,2,3, 我们都能一次拿完。

    Java Solution:

    Runtime beats 6.87% 

    完成日期:07/10/2017

    关键词:Brainteaser

    关键点:因为我们只能拿1,2,3块石头,所以4这个数字就是关键

     1 public class Solution 
     2 {
     3     public boolean canWinNim(int n) 
     4     {
     5         if(n % 4 == 0)
     6             return false;
     7         else
     8             return true;
     9     }
    10 }

    参考资料:

    http://www.cnblogs.com/grandyang/p/4873248.html

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    调用外部 DLL 中的函数(显示调用)
    模式窗体与非模式窗体
    使用PChar和string类型时的内存分配技术
    保密卡程序的编写
    Dll 使用 PChar 参数的小例子
    delphi动态创建组件的颜色
    Dll 模式窗口与非模式窗口
    调用外部 DLL 中的函数(隐式调用)
    内核读写只读内存方法总结[Delphi描述][转帖]
    delphi资源文件制作及使用详解
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7148670.html
Copyright © 2011-2022 走看看