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

    解题方案:

    因为你先手,所以:

    1. n <= 3 , 你赢;

    2. n == 4,  你输;

    3. n == 5,  你第一次取1个,无论对手取几个,你赢;

    4. n == 6,  你第一次取2个,无论对手取几个,你赢;

    5. n == 7, 你第一次取3个, 无论对手取几个,你赢;

    6. n == 8, 你输;

    以此类推....

     1 class Solution {
     2 public:
     3     bool canWinNim(int n) {
     4         if (n <= 3) {
     5             return true;
     6         }
     7         
     8         if (n % 4 == 0) {
     9             return false;
    10         }
    11         
    12         return true;
    13     }
    14 };
  • 相关阅读:
    python 读execl文件
    git 命令 个人备忘录
    python-django后端,富文本编辑器防XSS漏洞攻击,过滤富文本XSS
    mi
    Glance docker安装 cinder
    keystore glance
    openstack管理docker管理
    lvm 磁盘 数据库 wordpress 参考答案
    docker
    wordpress
  • 原文地址:https://www.cnblogs.com/skycore/p/4881845.html
Copyright © 2011-2022 走看看