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 };
  • 相关阅读:
    bzoj1996
    bzoj2839
    bzoj1304
    bzoj1097
    bzoj4547
    bzoj3379
    bzoj3090
    树莓派/Debian 构建LAMP Web服务器并搭建WordPress博客(一)
    树莓派/Debian Apache2 配置自建 CA 实现 HTTPS(SSL) 服务
    树莓派/Debian Apache2 实现 HTTPS(SSL) 服务
  • 原文地址:https://www.cnblogs.com/skycore/p/4881845.html
Copyright © 2011-2022 走看看