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;

  • 相关阅读:
    Java(八)——面向对象(4)-抽象类与接口
    Java(七)——面向对象(3)-多态
    Java(六)——面向对象(2)-继承
    Java(五)——面向对象(1)-基础
    Java(四)——数组
    Java(三)——流程控制
    Java(二)——Java基础
    易忘小技巧--yum
    网络测速命令--speedtest
    大型网站架构技术读后感
  • 原文地址:https://www.cnblogs.com/bonelee/p/8546379.html
Copyright © 2011-2022 走看看