zoukankan      html  css  js  c++  java
  • Nim Game 解答

    Question

    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:

    1. 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?

    Solution 1 -- DP

    传统的方法是DP。我们认为比赛只有两个状态:win, not win

    F(x) = (!F(x - 1)) || (!F(x - 2)) || (!F(x - 3))

    当对手不是全赢时,玩家即是赢。

    Time complexity O(n), space cost O(1)

     1 public class Solution {
     2     public boolean canWinNim(int n) {
     3         boolean first = true, second = true, third = true;
     4         for (int i = 3; i < n; i++) {
     5             boolean tmp = (!first) || (!second) || (!third);
     6             first = second;
     7             second = third;
     8             third = tmp;
     9         }
    10         return third;
    11     }
    12 }

    Solution 2 -- Math

    这道题其实是个数学问题。根据Discuss上的帖子,有一个结论:

    Theorem: The first one who got the number that is multiple of 4 (i.e. n % 4 == 0) will lost, otherwise he/she will win.

    1. Base case

    When number = 4, the player loses.

    2. Induction

    Hypothesis: we assume that number = 4 * k, the player will lose.

    When number = 4 * (k + 1), after the player moves stones, the number becomes (4 * k + 3) or (4 * k + 2) or (4 * k + 3). So the advisor can always make number for next round to be 4 * k. Thus, the player will lose.

    1 public class Solution {
    2     public boolean canWinNim(int n) {
    3         return !((n % 4) == 0);
    4     }
    5 }
  • 相关阅读:
    as3的InteractivePNG例子
    HttpWebRequest模拟POST提交防止中文乱码
    net发布的dll方法和类显示注释信息(字段说明信息)[图解]
    IP地址、手机归属和身份证查询接口
    一些好用的开源控件
    c# 操作IIS应用程序池
    c# 获取电脑硬件信息通用查询类[测试通过]
    C# 操作线程的通用类[测试通过]
    几款浏览器JavaScript调试工具
    Microsoft SQL Server 2005 提供了一些工具来监控数据库
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4944822.html
Copyright © 2011-2022 走看看