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
相关推荐
放羊郎3 小时前
基于ORB-SLAM2算法的优化工作
人工智能·算法·计算机视觉
mask哥3 小时前
力扣算法java实现汇总整理(上)
java·算法·leetcode
如果'\'真能转义说4 小时前
OOXML 文档格式剖析:哈希、ZIP结构与识别
xml·算法·c#·哈希算法
梦梦代码精6 小时前
BuildingAI 上部署自定义工作流智能体:5 个实用技巧
大数据·人工智能·算法·开源软件
Zephyr_07 小时前
Leedcode算法题
java·算法
流年如夢7 小时前
栈和列队(LeetCode)
数据结构·算法·leetcode·链表·职场和发展
Hello.Reader8 小时前
算法基础(十)——分治思想把大问题拆成小问题
java·开发语言·算法
逻辑驱动的ken9 小时前
Java高频考点场景题24
java·开发语言·面试·职场和发展·求职招聘
绛橘色的日落(。・∀・)ノ9 小时前
机器学习之评估与偏差方差分析
算法