• 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;
            
        }
    };
  • 相关阅读:
    LeetCode
    在linux服务器下部署python工程(爬虫)
    linux安装python3.6 及 beautifulsoup
    HDU 1561 The more, The Better[树形dp/01背包]
    POJ 3107 Godfather[树的重心]
    POJ 1655 Balancing Act[树的重心/树形dp]
    HDU 2169 Computer[树形dp]
    HDU
    POJ1721--CARDS [置换]
    POJ 1026 Cipher[置换]
  • 原文地址:https://www.cnblogs.com/Reindeer/p/5624964.html
Copyright © 2020-2023  润新知