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
相关推荐
吞下星星的少年·-·10 分钟前
牛客周赛 119B题(贪心)
算法·贪心
NEFU_Jyj19 分钟前
牛客周赛R166(max型瓶颈最短路,前后缀DP合并)
算法·深度优先
Tisfy28 分钟前
LeetCode 3644.排序排列:不对则与(脑筋急转弯)
数据结构·算法·leetcode·题解·位运算
文丑颜不良啊2 小时前
LeetCode576~600题目解析
java·leetcode
lisw052 小时前
分岔论揭示演化突变密码
开发语言·算法·数学建模
aqiu1111112 小时前
C++ TopK:使用 nth_element 快速求最小 K 个数(蓝桥杯 / LeetCode 可用)
算法
Suprman2 小时前
平面排版问题的数学建模与算法设计
算法·数学建模·排序算法·排版套料
FPGA信号处理2 小时前
【应用随机过程】:更新过程与马尔可夫链入门
算法·概率论
重生之小比特2 小时前
【算法拾光】二分查找|在排序数组中查找元素的第一个和最后一个位置 + 搜索旋转排序数组
数据结构·算法·排序算法
吴可可1232 小时前
DXF与AAMA格式转换模块推荐
算法