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.

    Hint:

    1. If there are 5 stones in the heap, could you figure out a way to remove the stones such that you will always be the winner

    本体你只要确保倒数第5个你能拿,然后确保倒数9个你能拿。。以此类推,后面都是4的倍数,因而从后向前数,你只要保证能拿到最后一个是4的倍数的前面一个石头即可。

    因而前面最多可以放3个石头,后面是4的倍数。所以只要石头的个数不能被4整除,你就能确保自己能赢

    class Solution {
    public:
        bool canWinNim(int n) {
            return n%4!=0;
        }
    };
  • 相关阅读:
    vue-slot插槽
    js中filter函数
    js异步处理
    js变量提升
    js中的4种函数调用模式
    js方法
    Javascript中的闭包 O__O "…
    js实现瀑布流以及加载效果
    2D转换下的zoom和transform:scale的区别
    [转]JavaScript与元素间的抛物线轨迹运动
  • 原文地址:https://www.cnblogs.com/csudanli/p/5324730.html
Copyright © 2011-2022 走看看