zoukankan      html  css  js  c++  java
  • LeetCode 292 Nim Game(Nim游戏)

    翻译

    你正在和你的朋友们玩以下这个Nim游戏:桌子上有一堆石头。每次你从中去掉1-3个。谁消除掉最后一个石头即为赢家。你在取出石头的第一轮。
    
    你们中的每个人都有着聪明的头脑和绝佳的策略。写一个函数来确定对于给定的数字是否你能够赢得这场比赛。
    
    比如,假设堆中有4个石头,那么你永远也无法赢得比赛:不管你移除了1、2或3个石头,最后一个石头都会被你的朋友所移除。

    原文

    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.

    分析

    题目一開始不是非常理解,由于朋友假设有2个、3个、多个的情况是全然不一样的呐,后来细致一看原文第一句withyourfriend,发现仅仅是和1个朋友玩游戏。

    于是我设定了一个推断条件

    bool yourTrun = true;

    后面巴拉巴拉写了一堆代码全错……

    加上一天的劳苦我開始趴着睡觉了,脑子里还在回忆。忽然发现:

    1-true
    2-true
    3-true
    4-false
    5-true
    6-true
    7-true
    8-false

    然后抬起头又一次写了一遍:

    bool canWinNim(int n) {
        if ((n - 1) % 4 == 0 || (n - 2) % 4 == 0 || (n - 3) % 4== 0) return true;       
        else return false;             
    }

    哇。通过了,感觉整理整理:

    bool canWinNim(int n) {
        return (n - 1) % 4 == 0 || (n - 2) % 4 == 0 || (n - 3) % 4 == 0;
    }

    继续整理。原来这么简单呐:

    bool canWinNim(int n) {
        return n % 4 != 0;
    }

    忽然就不困了。

    ^_^

    代码

    class Solution {
    public:      
        bool canWinNim(int n) {
            return n % 4 != 0;
        }
    };
  • 相关阅读:
    大同世界的Java 和.NET 开发
    关于Memcached 你了解多少?
    C#二进制与字符串之间的相互转换
    Nopcommerce主要用到的技术及特点
    小程序之路
    .NET方面的框架的整理和总结
    如何将FastReportOnlineDesign 灵活的应用到C/S B/S 程序当中?
    WebApi 的CRUD 的方法的应用
    关于EF 通用增删改查的封装
    基于Json序列化和反序列化通用的封装
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/7364981.html
Copyright © 2011-2022 走看看