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
相关推荐
小江的记录本3 分钟前
【分布式】分布式核心组件——分布式ID生成:雪花算法、号段模式、美团Leaf、百度UidGenerator、时钟回拨解决方案
分布式·后端·算法·缓存·性能优化·架构·系统架构
leobertlan7 小时前
好玩系列:用20元实现快乐保存器
android·人工智能·算法
青梅橘子皮7 小时前
C语言---指针的应用以及一些面试题
c语言·开发语言·算法
_Evan_Yao7 小时前
技术成长周记06|面试中看清差距,新项目点燃热情
面试·职场和发展
_深海凉_8 小时前
LeetCode热题100-有效的括号
linux·算法·leetcode
被开发耽误的大厨11 小时前
1、==、equals、hashCode底层原理?重写场景?
算法·哈希算法
haina201911 小时前
《品牌观察》专访海纳AI:引领AI面试测评新时代
人工智能·面试·职场和发展
WolfGang00732111 小时前
代码随想录算法训练营 Day38 | 动态规划 part11
算法·动态规划
Raink老师12 小时前
【AI面试临阵磨枪】什么是 MCP(Model Control Protocol)、A2A(Agent-to-Agent)协议?
人工智能·面试·职场和发展·ai 面试
松☆12 小时前
C++ 算法竞赛题解:P13569 [CCPC 2024 重庆站] osu!mania —— 浮点数精度陷阱与 `eps` 的深度解析
开发语言·c++·算法