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

  • 相关阅读:
    运维文档的几点看法
    cmpp短信网关对接MSGID问题
    一文带解读C# 动态拦截覆盖第三方进程中的函数(外挂必备)
    C#中的解构
    如何科学破解慢SQL?
    c# HttpClient 上传文件并带参
    React 页面跳转传值
    Mysql 优化:status这类字段适合加索引吗?
    PHP数组高效去重
    PHP unset()、array_unique()的坑
  • 原文地址:https://www.cnblogs.com/yrbbest/p/5042259.html
Copyright © 2011-2022 走看看