zoukankan      html  css  js  c++  java
  • 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;

  • 相关阅读:
    删除难以删除的文件
    DLL创建与使用
    Springboot多文件上传
    解决javaweb项目启动端口号被占用
    pl/sql 导出数据库表dmp文件并导入数据库过程
    Spring Boot 静态资源处理
    Consider defining a bean of type错误
    SpringBoot+layUI上传图片功能
    jQuery改变html页面样式
    Springboot启动后默认访问页面修改
  • 原文地址:https://www.cnblogs.com/bonelee/p/8546379.html
Copyright © 2011-2022 走看看