LeetCode刷题实战292:Nim 游戏

算法的重要性,我就不多说了吧,想去大厂,就必须要经过基础知识和业务逻辑面试+算法面试。所以,为了提高大家的算法能力,这个公众号后续每天带大家做一道算法题,题目就从LeetCode上面选 !

今天和大家聊的问题叫做 Nim 游戏,我们先来看题面:

https://leetcode-cn.com/problems/nim-game/

You are playing the following Nim Game with your friend:

  • Initially, there is a heap of stones on the table.

  • You and your friend will alternate taking turns, and you go first.

  • On each turn, the person whose turn it is will remove 1 to 3 stones from the heap.

  • The one who removes the last stone is the winner.

Given n, the number of stones in the heap, return true if you can win the game assuming both you and your friend play optimally, otherwise return false.

你和你的朋友,两个人一起玩 Nim 游戏:

  • 桌子上有一堆石头。

  • 你们轮流进行自己的回合,你作为先手。

  • 每一回合,轮到的人拿掉 1 - 3 块石头。

  • 拿掉最后一块石头的人就是获胜者。

假设你们每一步都是最优解。请编写一个函数,来判断你是否可以在给定石头数量为 n 的情况下赢得游戏。如果可以赢,返回 true;否则,返回 false 。

示例

示例 1:

输入:n = 4
输出:false 
解释:如果堆中有 4 块石头,那么你永远不会赢得比赛;
  因为无论你拿走 1 块、2 块 还是 3 块石头,最后一块石头总是会被你的朋友拿走。

示例 2:

输入:n = 1
输出:true

示例 3:

输入:n = 2
输出:true

解题

有史以来最少代码量的解法,虽然解法很简单,但是题目还是蛮有意思的,题目说给我们一堆石子,每次可以拿一个两个或三个,两个人轮流拿,拿到最后一个石子的人获胜,现在给我们一堆石子的个数,问我们能不能赢。那么我们就从最开始分析,由于是我们先拿,那么3个以内(包括3个)的石子,我们直接赢,如果共4个,那么我们一定输,因为不管我们取几个,下一个人一次都能取完。如果共5个,我们赢,因为我们可以取一个,然后变成4个让别人取,根据上面的分析我们赢,所以我们列出1到10个的情况如下:


1.Win
2.Win
3.Win
4.Lost
5.Win
6.Win
7.Win
8.Lost
9.Win
10.Win
由此我们可以发现规律,只要是4的倍数个,我们一定会输,所以对4取余即可

class Solution {
    public boolean canWinNim(int n) {
        return n % 4 != 0;
    }
}

好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。

上期推文:

LeetCode1-280题汇总,希望对你有点帮助!

LeetCode刷题实战281:锯齿迭代器

LeetCode刷题实战282:给表达式添加运算符

LeetCode刷题实战283:移动零

LeetCode刷题实战284:顶端迭代器

LeetCode刷题实战285:二叉搜索树中的顺序后继

LeetCode刷题实战286:墙和门

LeetCode刷题实战287:寻找重复数

LeetCode刷题实战288:单词的唯一缩写

LeetCode刷题实战289:生命游戏

LeetCode刷题实战290:单词规律

LeetCode刷题实战292:Nim 游戏_第1张图片

你可能感兴趣的:(算法导论,toolbar,consul,coursera,im)