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
相关推荐
无限进步_18 小时前
【C语言&数据结构】对称二叉树:镜像世界的递归探索
c语言·开发语言·数据结构·c++·git·算法·visual studio
星辞树18 小时前
揭秘阿里 DIN:当深度学习遇上“千物千面”
算法
刘立军18 小时前
如何选择FAISS的索引类型
人工智能·算法·架构
小芒果_0118 小时前
整理归并排序
c++·算法·排序算法·信息学奥赛
牛三金18 小时前
匿踪查询沿革-Private Information Retrieval(PIR)
算法·安全
德育处主任18 小时前
『NAS』在群晖部署一个文件加密工具-hat.sh
前端·算法·docker
星辞树18 小时前
从 L1/L2 到 Dropout:深度解析正则化,为何推荐系统“只能练一次”?
算法
玖剹18 小时前
队列+宽搜(bfs)
数据结构·c++·算法·leetcode·宽度优先
mit6.82419 小时前
01bfs|前缀和的前缀和
算法
wen__xvn19 小时前
代码随想录算法训练营DAY11第五章 栈与队列part02
算法