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 }
  • 相关阅读:
    find命令详解
    wget命令
    国内镜像源
    向linux服务器上传下载文件方式收集
    一些初学shell自己写的一些练习题脚本
    在Linux系统下mail命令的用法
    MAC 下安装 SVN
    天气预报api整理
    pdi vcard-2.1
    Android Studio 问题锦集【持续更新】
  • 原文地址:https://www.cnblogs.com/ireneyanglan/p/4944822.html
Copyright © 2011-2022 走看看