zoukankan      html  css  js  c++  java
  • 292. 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.

    answer:

    当石子数为1,2,3时,先手可一次拿走,先手必胜;

    当石子数为4时,不论先手拿1,2,还是3,后手必胜;

    当石子数为5是,先手先拿一个,后手面对石子数为4的情况,先手必胜;

    ......

    所以,当石子数是4的倍数时,后手必胜,否则先手胜。

    后手获胜的策略为:每次取石子的数量,与上一次先手所取石子的数量相加为4.

    先手获胜的策略为:每次取石子的数量,都令剩余石子的数量为4的倍数。

    class Solution {
    public:
        bool canWinNim(int n) {
            if(n%4==0)
            return false;
            else
            return true;
            
        }
    };
  • 相关阅读:
    delphi XE8 for android ----一个无意闯入的世界
    不能Ping和telnet的
    syslog-ng内容讲解
    《信息安全系统设计与实现》学习笔记7
    缓冲区溢出实验
    2.3.1测试
    鲲鹏服务器测试
    cat userlist
    需求分析
    《信息安全系统设计与实现》学习笔记5
  • 原文地址:https://www.cnblogs.com/Reindeer/p/5624964.html
Copyright © 2011-2022 走看看