[LeetCode]--292. 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

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:

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?
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.

这是博弈论中极为经典的尼姆游戏。有总数为n的石头,每个人可以拿1~m个石头,两个人交替拿,拿到最后一个的人获胜。究竟是先手有利,还是后手有利?

1个石子,先手全部拿走;
2个石子,先手全部拿走;
3个石子,先手全部拿走;
4个石子,后手面对的是先手的第1,2,3情况,后手必胜;
5个石子,先手拿走1个让后手面对第4种情况,后手必败;
6个石子,先手拿走2个让后手面对第4种情况,后手必败;
……

容易看出来,只有当出现了4的倍数,先手无可奈何,其余情况先手都可以获胜。 (石子数量为4的倍数)

后手的获胜策略十分简单,每次取石子的数量,与上一次先手取石子的数量和为4即可; (石子数量不为4的倍数)先手的获胜策略也十分简单,每次都令取之后剩余的石子数量为4的倍数(4*0=0,直接拿光),他就处于后手的位置上,利用上一行的策略获胜。

public boolean canWinNim(int n) {
        return n % 4 != 0;
    }
目录
相关文章
|
3月前
leetcode:292. Nim 游戏(数学推理)
leetcode:292. Nim 游戏(数学推理)
18 0
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode contest 200 5476. 找出数组游戏的赢家 Find the Winner of an Array Game
LeetCode 390. Elimination Game
给定一个从1 到 n 排序的整数列表。 首先,从左到右,从第一个数字开始,每隔一个数字进行删除,直到列表的末尾。 第二步,在剩下的数字中,从右到左,从倒数第一个数字开始,每隔一个数字进行删除,直到列表开头。 我们不断重复这两步,从左到右和从右到左交替进行,直到只剩下一个数字。 返回长度为 n 的列表中,最后剩下的数字。
72 0
LeetCode 390. Elimination Game
LeetCode 292. Nim Game
你和你的朋友,两个人一起玩 Nim游戏:桌子上有一堆石头,每次你们轮流拿掉 1 - 3 块石头。 拿掉最后一块石头的人就是获胜者。你作为先手。 你们是聪明人,每一步都是最优解。 编写一个函数,来判断你是否可以在给定石头数量的情况下赢得游戏。
55 0
LeetCode 292. Nim Game
|
存储 算法
LeetCode 289. Game of Life
如果活细胞周围八个位置的活细胞数少于两个,则该位置活细胞死亡; 如果活细胞周围八个位置有两个或三个活细胞,则该位置活细胞仍然存活; 如果活细胞周围八个位置有超过三个活细胞,则该位置活细胞死亡; 如果死细胞周围正好有三个活细胞,则该位置死细胞复活;
48 0
LeetCode 289. Game of Life
|
算法 索引
LeetCode 55. Jump Game
给定一个非负整数数组,您最初定位在数组的第一个索引处。 数组中的每个元素表示该位置的最大跳转长度。 确定您是否能够到达最后一个索引。
71 0
LeetCode 55. Jump Game
|
算法 索引
LeetCode 45. Jump Game II
给定一个非负整数数组,初始位置在索引为0的位置,数组中的每个元素表示该位置的能够跳转的最大部署。目标是以最小跳跃次数到达最后一个位置(索引)。
50 0
LeetCode 45. Jump Game II
|
决策智能
LeetCode之Nim Game
LeetCode之Nim Game
101 0
|
算法 Java C#
LeetCode刷题292-简单-Nim游戏
LeetCode刷题292-简单-Nim游戏
191 0
LeetCode刷题292-简单-Nim游戏