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
相关推荐
随意起个昵称5 小时前
区间dp-基础题目1(石子合并)
算法·动态规划
吞下星星的少年·-·6 小时前
线段树模板
算法
段一凡-华北理工大学6 小时前
2026 高炉炼铁智能化技术全景与演进路径~系列文章11:演进路径与行业未来
大数据·网络·人工智能·算法·工业智能体·高炉炼铁智能化
凯瑟琳.奥古斯特6 小时前
高阶子查询题目精炼
开发语言·数据库·python·职场和发展·数据库开发
叶小鸡6 小时前
小鸡玩算法-力扣HOT100-多维动态规划
算法·leetcode·动态规划
星马梦缘7 小时前
aaaaa
数据结构·c++·算法
菜菜的顾清寒7 小时前
力扣HOT100(42)链表-随机链表的复制
算法·leetcode·链表
lqqjuly7 小时前
模型剪枝与稀疏化:理论、算法与可运行实现
人工智能·算法·剪枝
凯瑟琳.奥古斯特8 小时前
数据库原理选择题精选
数据库·python·职场和发展
逻辑君8 小时前
Foresight研究报告【20260011】
人工智能·线性代数·算法·矩阵