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
相关推荐
FONE_Platform1 分钟前
FONE食品饮料行业全面预算解决方案:构建韧性增长
人工智能·算法·全面预算·全面预算管理系统·企业全面预算
月明长歌11 分钟前
【码道初阶】【Leetcode94&144&145】二叉树的前中后序遍历(非递归版):显式调用栈的优雅实现
java·数据结构·windows·算法·leetcode·二叉树
DanyHope26 分钟前
《LeetCode 49. 字母异位词分组:哈希表 + 排序 全解析》
算法·leetcode·哈希算法·散列表
iAkuya29 分钟前
(leetcode) 力扣100 15轮转数组(环状替代)
数据结构·算法·leetcode
杰克尼31 分钟前
蓝桥云课-5. 花灯调整【算法赛】
java·开发语言·算法
.小墨迹32 分钟前
C++学习之std::move 的用法与优缺点分析
linux·开发语言·c++·学习·算法·ubuntu
努力学算法的蒟蒻39 分钟前
day38(12.19)——leetcode面试经典150
算法·leetcode·面试
搬砖魁首1 小时前
ZK-ALU-在有限域上实现乘法和除法
算法·zk·alu·域运算·算术逻辑单元·模乘·蒙哥马利模约简
iAkuya1 小时前
(leetcode)力扣100 17缺失的第一个正数(哈希)
算法·leetcode·哈希算法
断剑zou天涯1 小时前
【算法笔记】树状数组IndexTree
java·笔记·算法