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
相关推荐
2401_8812444010 小时前
P3808 AC 自动机(简单版)
算法
Jayden_Ruan10 小时前
C++十进制转二进制
数据结构·c++·算法
Haooog11 小时前
98.验证二叉搜索树(二叉树算法题)
java·数据结构·算法·leetcode·二叉树
Macre Aegir Thrym12 小时前
MINIST——SVM
算法·机器学习·支持向量机
Young_Zn_Cu13 小时前
LeetCode刷题记录(持续更新中)
算法·leetcode
天选之女wow13 小时前
【代码随想录算法训练营——Day31】贪心算法——56.合并区间、738.单调递增的数字、968.监控二叉树
算法·leetcode·贪心算法
lixinnnn.13 小时前
贪心:火烧赤壁
数据结构·c++·算法
小小前端_我自坚强13 小时前
前端算法相关详解
前端·算法
前端 贾公子13 小时前
《Vuejs设计与实现》第 5 章(非原始值响应式方案)下 Set 和 Map 的响应式代理
数据结构·算法
WWZZ202515 小时前
ORB_SLAM2原理及代码解析:SetPose() 函数
人工智能·opencv·算法·计算机视觉·机器人·自动驾驶