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
相关推荐
Zootopia62622 分钟前
多架 eVTOL集群排班调度方案思考
人工智能·算法·数学建模·matlab·动态规划·无人机·evtol
和裕39 分钟前
年度框架直供 vs 零散按需采购:定制纸箱采购成本、交付与服务核心区别全对比
大数据·运维·网络·人工智能·算法
朝朝辞暮i44 分钟前
C++ 第 13 课:值传递 —— 为什么函数里改了,外面却没变?
java·c++·算法
淡海水1 小时前
02-02-原理篇-分代GC
算法·unity·c#·游戏引擎·.net·gc
无忧.芙桃2 小时前
C++语言原理与实践(十):vector类的底层实现
开发语言·c++·算法
乐迪信息2 小时前
AI防爆摄像机,监测港口船舶航行偏航隐患
大数据·人工智能·深度学习·算法·计算机视觉
0+1113 小时前
算法 --模拟
c++·算法·leetcode
青山是哪个青山3 小时前
LeetCode 300:最长递增子序列
算法
hetao17338373 小时前
2026-10-01~02 hetao1733837 的刷题记录
c++·算法
小虎牙^O^3 小时前
模糊数学综合评价:从模糊数学到建模评价类模型
人工智能·算法