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
相关推荐
荼蘼1 小时前
基于 KNN 算法的手写数字识别项目实践
人工智能·算法·机器学习
运维成长记1 小时前
关于linux运维 出现高频的模块认知
运维·职场和发展·云计算
Yuroo zhou1 小时前
IMU的精度对无人机姿态控制意味着什么?
单片机·嵌入式硬件·算法·无人机·嵌入式实时数据库
jackzhuoa2 小时前
java小白闯关记第一天(两个数相加)
java·算法·蓝桥杯·期末
Codeking__3 小时前
链表算法综合——重排链表
网络·算法·链表
minji...3 小时前
数据结构 堆(4)---TOP-K问题
java·数据结构·算法
技术卷4 小时前
详解力扣高频SQL50题之610. 判断三角形【简单】
sql·leetcode·oracle
AI_Keymaker4 小时前
一句话生成3D世界:腾讯开源混元3D模型
算法
Leon_vibs4 小时前
当 think 遇上 tool:深入解析 Agent 的规划之道
算法
旧时光巷4 小时前
【机器学习-2】 | 决策树算法基础/信息熵
算法·决策树·机器学习·id3算法·信息熵·c4.5算法