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
相关推荐
rit843249912 分钟前
人工鱼群算法AFSA优化支持向量机SVM,提高故障分类精度
算法·支持向量机·分类
佩佩(@ 。 @)35 分钟前
嵌入式:走馬燈-stm32GPIOF_LED9、10; GPIOE_D10、D12 流水綫蜂鸣器
stm32·嵌入式硬件·算法
知彼解己41 分钟前
字符串大数相加:从初稿到优化的思路演进
java·开发语言·算法
haing20191 小时前
使用deboor法计算三次B样条曲线在参数为u处的位置的方法介绍
算法·b样条曲线·deboor
qq_352109521 小时前
旋转数字矩阵 od
算法
大阳1231 小时前
51单片机4(温度传感器DS18B20)
开发语言·单片机·嵌入式硬件·算法·51单片机
iナナ1 小时前
Java优选算法——二分查找
数据结构·算法·leetcode
l1t2 小时前
利用美团龙猫添加xlsx的sheet.xml读取sharedStrings.xml中共享字符串输出到csv功能
xml·c语言·数据结构·人工智能·算法·解析器
宇钶宇夕3 小时前
西门子 S7-200 SMART PLC 编程:转换 / 定时器 / 计数器指令详解 + 实战案例(指令讲解篇)
运维·算法·自动化
我叫汪枫3 小时前
Spring Boot图片验证码功能实现详解 - 从零开始到完美运行
java·前端·javascript·css·算法·html