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.

    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?

    链接: http://leetcode.com/problems/nim-game/

    题解:

    看来我的推测是对的。jianchao.li真的加了很多很多数学有关的趣题...这个也是很有意思,第一次接触是在小时候看古畑任三郎第一季最后一集里老爷和数学家(毛利小五郎)对弈,玩的就是这个游戏。关键就是4的倍数一定是false,所以我们直接返回结果。

    public class Solution {
        public boolean canWinNim(int n) {
            return n % 4 != 0;
        }
    }

    二刷:

    Java:

    Time Complexity - O(1), Space Complexity - O(1)

    public class Solution {
        public boolean canWinNim(int n) {
            return n % 4 != 0;
        }
    }

    三刷:

    Java:

    public class Solution {
        public boolean canWinNim(int n) {
            return n % 4 != 0;
        }
    }

    Reference:

    https://leetcode.com/discuss/63725/theorem-all-4s-shall-be-false

    https://leetcode.com/discuss/63978/one-line-o-1-solution-and-explanation

  • 相关阅读:
    C#面向对象的三大特性概述
    SQL Server 低版本还原高版本的数据库
    将表转化成脚本的存储过程
    iis安装失败解决方法
    kafka consumer 配置详解
    C#解析XML文件
    blat
    REST接口POST方法发送文件到服务器(C#)
    http://www.codeproject.com/Questions/117324/uploadfileincwithHttpWebRequest
    PDF Password Remover
  • 原文地址:https://www.cnblogs.com/yrbbest/p/5042259.html
Copyright © 2011-2022 走看看