leetcode 292. Nim Game

You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

一开始我是用斐波那契数列思路求解,因为f(n) =  !f(n-1) or !f(n-2) or !f(n-3),但是经过深入观察发现,答案的规律就在于数字是否为4的倍数。面试遇到这种题目就只能多多观察,总结规律再下手!

复制代码
class Solution(object):
    def canWinNim(self, n):
        """
        :type n: int
        :rtype: bool
        """
        # 1,2,3 => true
        # 4 => false
        # 5,6,7 => true, =1,2,3+f(4)
        # 8 => 1,2,3+f(5,6,7) = false
        # 9 => 1,2,3+f(6,7,8) = true
        # 10 => 1+2,3+f(9,8,7) = true
        # 11 => 1,2,3+f(10,9,8) = true
        # 12 => 1,2,3+f(11,10,9) = false
        # 13 => 1,2,3+f(12,11,10) = true
        # 14 => 1,2,3+f(13,12,11) = true
        # 15 => 
        # rule: 3true 1false 3true 1false ...
        return n % 4 != 0
        
        # iter solution, but time limit
        if n <= 3:
            return True
        a = b = c = True    
        for i in xrange(4, n+1):
            t = (not a) or (not b) or (not c) 
            a = b
            b = c
            c = t
        return c
复制代码

 4的倍数还可以 return (n & 0b11) != 0;

posted @   bonelee  阅读(165)  评论(0编辑  收藏  举报
编辑推荐:
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示