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
相关推荐
ballball~~5 分钟前
ISP-CCM(Color Correction Matrix)
图像处理·数码相机·算法
sheeta199826 分钟前
LeetCode 每日一题笔记 日期:2025.03.24 题目:2906.构造乘积矩阵
笔记·leetcode·矩阵
Sunshine for you34 分钟前
实时操作系统中的C++
开发语言·c++·算法
中科院提名者1 小时前
BPE 算法的硬核拆解——理解词表(Vocabulary)是如何从零训练出来的,以及字符串是如何被切碎的
算法
「QT(C++)开发工程师」1 小时前
C++11三大核心特性深度解析:类型特征、时间库与原子操作
java·c++·算法
乐分启航1 小时前
SliMamba:十余K参数量刷新SOTA!高光谱分类的“降维打击“来了
java·人工智能·深度学习·算法·机器学习·分类·数据挖掘
你真是饿了3 小时前
算法专题二:滑动窗口
算法
ccLianLian3 小时前
数论·约数
数据结构·算法
会编程的土豆3 小时前
【数据结构与算法】最短路径---Dijkstra 算法
数据结构·c++·算法
2401_879693873 小时前
C++中的观察者模式实战
开发语言·c++·算法