zoukankan      html  css  js  c++  java
  • Coins in a Line

    There are n coins in a line. Two players take turns to take one or two coins from right side until there are no more coins left. The player who take the last coin wins.

    Could you please decide the first play will win or lose?

    这是一类博弈类的DP问题.

    博弈问题的基本解决思路是:

    state:定义其中一个人的状态.

    function:考虑两个人的状态做更新,即根据相互对抗的一个关系来做决策.

    博弈类题目适合从大的状态往小的状态递推,非常适合记忆化搜索.不过这题本身比较简单,可以已经bottom-up来做.

    这里分析f[i]为还剩i枚硬币的时候先手能否获胜.我们考虑递推状态.先手在f[i]可以获胜,即他拿了最后一枚或者两枚硬币.这样在f[i-1]后者f[i-2]时是后手获胜的,所以有递推关系f[i] = !f[i-1]||!f[i-2]

    初始化,还剩0枚硬币时先手肯定输.还剩1,2枚硬币时先手能赢.但是最后的结果取什么呢.是还剩0枚硬币,还是n枚.其实我们是从还有n枚硬币,考虑这时候的博弈状态考量的,所以是f[n].代码如下:

    class Solution:
        # @param n: an integer
        # @return: a boolean which equals to True if the first player will win
        def firstWillWin(self, n):
            if n <= 0:
                return False
            if n <= 2:
                return True
            f = [False] *(n+1)
            f[1] = True
            f[2] = True
            
            for i in xrange(2,n+1):
                f[i] = (not f[i-1]) or (not f[i-2])
                
            return f[n]
  • 相关阅读:
    Postman模拟后端服务(mock server)
    Fiddler常用的几个功能
    Postman常用的几个功能
    Postman常用功能详解,常用请求方法
    sql小技巧
    postman接口数据关联
    postman批量发送多个请求
    sql去重查询语句
    pytho接口自动化-session
    charles抓包使用教程
  • 原文地址:https://www.cnblogs.com/sherylwang/p/5597721.html
Copyright © 2011-2022 走看看