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;
        }
    };
  • 相关阅读:
    十大接口
    ORM表之间高级设计
    响用模块
    异常模块的使用
    解析模块的使用
    渲染模板
    通达OA 11.7 后台sql注入getshell漏洞复现
    通达OA 11.5 SQL注入漏洞复现
    ThinkAdminV6 未授权访问and 任意文件查看 漏洞复现
    用友GRP-u8 XXE 漏洞复现
  • 原文地址:https://www.cnblogs.com/mfmdaoyou/p/7364981.html
Copyright © 2011-2022 走看看