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
相关推荐
小O的算法实验室8 小时前
IEEE TASE,基于MPC的多无人机协同搜索竞争群体优化方法
算法
城管不管8 小时前
重生——第十一次面试之挖财一面2026.8.19已OC
java·服务器·jvm·数据库·spring·面试·职场和发展
Tbisnic9 小时前
BGE-M3 算法详解:从模型架构到三种检索方式的数学原理
算法·自然语言处理·大模型·bert·transformer·注意力机制
Brilliantwxx9 小时前
【算法从零到千】【55-58】哈希位图+常见数学运算 接口
算法
空堂与归10 小时前
用户分群找不到规律?用K-Means聚类算法自动发现数据模式
算法·机器学习·kmeans·聚类
动词ing10 小时前
【C语言】自定义函数+指针入门
c语言·开发语言·算法
重生之后端学习11 小时前
283. 移动零[简单]✅
开发语言·数据结构·算法·leetcode·职场和发展
一只小小的芙厨11 小时前
基础数论总结
笔记·学习·算法
夜不会漫长13 小时前
C++入门(1)
开发语言·c++·算法
wen_zhufeng13 小时前
IndexTTS 2.5 技术报告
人工智能·算法·机器学习