Leetcode 292. Nim Game

Problem

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.

Algorithm

First find the transfer equation: If (n < 4), then f(n) = True. If (f(n-1) & f(n-2) & f(n-3) == 1), then f(n) = False. If (f(n-1) | f(n-2) | f(n-3) == 0), then f(n) = 1.

So if (n % 4 == 0), then f(n) = 0, else f(n) = 1.

Code

python3 复制代码
class Solution:
    def canWinNim(self, n: int) -> bool:
        return n % 4 > 0
相关推荐
学究天人6 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(补充卷9)
人工智能·线性代数·算法·数学建模·动态规划·原型模式·抽象代数
Keven_116 小时前
算法札记:图的存储方式
算法·图论
斯文的八宝粥6 小时前
SERL:让真机强化学习从“难用”走向“可复现”的强化学习框架 ----(4)算法篇(DrQ vs VICE)
算法
yangdaxiageo6 小时前
算法时代的“心智置顶“:《功夫女足》如何构建GEO正向飞轮
人工智能·科技·算法·aigc
ysa0510307 小时前
【板子】欧拉序
c++·笔记·算法·深度优先·图论
大耳朵糊涂7 小时前
链表的基础操作(二)
算法
拂拉氏7 小时前
【知识讲解】 红黑树的删除讲解
数据结构·算法·红黑树
初学者,亦行者7 小时前
算法设计与分析:动态规划 - TSP问题和0-1背包问题
c++·算法·动态规划
ward RINL7 小时前
# GPT-5.6-sol vs GPT-5.5 新题实测:非弹性碰撞物理题和稳定路由算法
网络·gpt·算法
灯澜忆梦7 小时前
【dp_1】爬楼梯 | 斐波那契数 | 第 N 个泰波那契数 | 三步问题
算法·golang