LeetCode 292 Nim Game(Nim游戏)

简介:

翻译

你正在和你的朋友们玩下面这个Nim游戏:桌子上有一堆石头,每次你从中去掉1-3个。谁消除掉最后一个石头即为赢家。你在取出石头的第一轮。

你们中的每一个人都有着聪明的头脑和绝佳的策略。写一个函数来确定对于给定的数字是否你可以赢得这场比赛。

例如,如果堆中有4个石头,那么你永远也无法赢得比赛:无论你移除了1、2或3个石头,最后一个石头都会被你的朋友所移除。

原文

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.

分析

题目一开始不是很理解,因为朋友如果有2个、3个、多个的情况是完全不一样的呐,后来仔细一看原文第一句withyourfriend,发现只是和1个朋友玩游戏。

于是我设定了一个判断条件

bool yourTrun = true;

后面巴拉巴拉写了一堆代码全错……

加上一天的劳累我开始趴着睡觉了,脑子里还在回想。忽然发现:

1-true
2-true
3-true
4-false
5-true
6-true
7-true
8-false

然后抬起头重新写了一遍:

bool canWinNim(int n) {
    if ((n - 1) % 4 == 0 || (n - 2) % 4 == 0 || (n - 3) % 4== 0) return true;       
    else return false;             
}

哇,通过了,感觉整理整理:

bool canWinNim(int n) {
    return (n - 1) % 4 == 0 || (n - 2) % 4 == 0 || (n - 3) % 4 == 0;
}

继续整理,原来这么简单呐:

bool canWinNim(int n) {
    return n % 4 != 0;
}

忽然就不困了。^_^

代码

class Solution {
public:      
    bool canWinNim(int n) {
        return n % 4 != 0;
    }
};
目录
相关文章
|
16天前
力扣-2029-石子游戏-‘屎山’代码
力扣-2029-石子游戏-‘屎山’代码
16 3
|
18天前
|
算法 数据挖掘 开发者
LeetCode题目55:跳跃游戏【python5种算法贪心/回溯/动态规划/优化贪心/索引哈希映射 详解】
LeetCode题目55:跳跃游戏【python5种算法贪心/回溯/动态规划/优化贪心/索引哈希映射 详解】
|
14天前
|
算法
【经典LeetCode算法题目专栏分类】【第9期】深度优先搜索DFS与并查集:括号生成、岛屿问题、扫雷游戏
【经典LeetCode算法题目专栏分类】【第9期】深度优先搜索DFS与并查集:括号生成、岛屿问题、扫雷游戏
|
14天前
|
算法 机器人
【经典LeetCode算法题目专栏分类】【第5期】贪心算法:分发饼干、跳跃游戏、模拟行走机器人
【经典LeetCode算法题目专栏分类】【第5期】贪心算法:分发饼干、跳跃游戏、模拟行走机器人
|
18天前
|
存储 算法 数据挖掘
力扣174题动态规划:地下城游戏(含模拟面试)
力扣174题动态规划:地下城游戏(含模拟面试)
|
18天前
|
SQL 算法 数据可视化
python 贪心算法 动态规划实现 跳跃游戏ll【力扣题45】
python 贪心算法 动态规划实现 跳跃游戏ll【力扣题45】
|
1月前
|
算法 测试技术 索引
【力扣】45.跳跃游戏Ⅱ
【力扣】45.跳跃游戏Ⅱ
|
13天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-2
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
13天前
|
算法 C++
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题-1
【数据结构与算法】:关于时间复杂度与空间复杂度的计算(C/C++篇)——含Leetcode刷题
|
14天前
|
索引
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值
【LeetCode刷题】二分查找:山脉数组的峰顶索引、寻找峰值