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
相关推荐
小雉系统8 小时前
BcoreOS安全通信架构:FsSession 抗算法后门安全设计
算法·安全·架构
唐墨12313 小时前
linux kernel 比较数据大小的宏定义
linux·算法
拂拉氏13 小时前
【知识讲解-题目讲解】 统计满足K约束的子字符串数量2 (滑动窗口+前缀和+二分查找+分析)
算法·前缀和·二分查找·滑动窗口
lsc_blog16 小时前
听到优化风声,先准备能由自己掌控的事
数据库·分布式·中间件·职场和发展·重构
通信小呆呆18 小时前
电子战抗干扰技术:当“不被干扰”成为一种系统
算法·通信·mimo·isac
笑容掩饰我的失落18 小时前
区块链从小白到精通(八):从零实现一个标准 ERC-20 代币(完整可运行代码)
算法·区块链·php·智能合约·哈希算法
Severus_black18 小时前
【C++初阶】Stack、Queue算法题大练兵!
c语言·c++·算法·stl
2601_9679791221 小时前
机器学习必修课:经典算法与Python实战
python·算法·机器学习·实战·课程
程序猿打工仔21 小时前
计算机基础(C语言)考编、专技岗
c语言·开发语言·算法