zoukankan      html  css  js  c++  java
  • [Swift]LeetCode375. 猜数字大小 II | Guess Number Higher or Lower II

    原文地址:https://www.cnblogs.com/strengthen/p/10278211.html 

    We are playing the Guess Game. The game is as follows:

    I pick a number from 1 to n. You have to guess which number I picked.

    Every time you guess wrong, I'll tell you whether the number I picked is higher or lower.

    However, when you guess a particular number x, and you guess wrong, you pay $x. You win the game when you guess the number I picked.

    Example:

    n = 10, I pick 8.
    
    First round:  You guess 5, I tell you that it's higher. You pay $5.
    Second round: You guess 7, I tell you that it's higher. You pay $7.
    Third round:  You guess 9, I tell you that it's lower. You pay $9.
    
    Game over. 8 is the number I picked.
    
    You end up paying $5 + $7 + $9 = $21.
    

    Given a particular n ≥ 1, find out how much money you need to have to guarantee a win.


    我们正在玩一个猜数游戏,游戏规则如下:

    我从 1 到 n 之间选择一个数字,你来猜我选了哪个数字。

    每次你猜错了,我都会告诉你,我选的数字比你的大了或者小了。

    然而,当你猜了数字 x 并且猜错了的时候,你需要支付金额为 x 的现金。直到你猜到我选的数字,你才算赢得了这个游戏。

    示例:

    n = 10, 我选择了8.
    
    第一轮: 你猜我选择的数字是5,我会告诉你,我的数字更大一些,然后你需要支付5块。
    第二轮: 你猜是7,我告诉你,我的数字更大一些,你支付7块。
    第三轮: 你猜是9,我告诉你,我的数字更小一些,你支付9块。
    
    游戏结束。8 就是我选的数字。
    
    你最终要支付 5 + 7 + 9 = 21 块钱。
    

    给定 n ≥ 1,计算你至少需要拥有多少现金才能确保你能赢得这个游戏。


    232ms

     1 class Solution {
     2     func getMoneyAmount(_ n: Int) -> Int {
     3         var memo:[[Int]] = [[Int]](repeating:[Int](repeating:0,count:n + 1),count:n + 1)
     4         return helper(1, n, &memo)
     5     }
     6     
     7     func helper(_ start:Int,_ end:Int,_ memo:inout [[Int]]) -> Int
     8     {
     9         if start >= end {return 0}
    10         if memo[start][end] > 0 {return memo[start][end]}
    11         var res:Int = Int.max
    12         for k in start...end
    13         {
    14             var t:Int = k + max(helper(start, k - 1, &memo), helper(k + 1, end, &memo))
    15             res = min(res, t)
    16         }
    17         memo[start][end] = res
    18         return res
    19     }
    20 }
  • 相关阅读:
    Extjs面板和布局初探
    XAMPP下apache部署网站,多个虚拟机(空间)配置
    安全配置织梦系统初探参考[转载]
    windows系统如何真正隐藏文件夹[转载]
    Siamese-RPN论文阅读
    线段树求和
    算法要点随记
    map使用示例
    算法准备之c++ sort使用示例
    编程要点随记
  • 原文地址:https://www.cnblogs.com/strengthen/p/10278211.html
Copyright © 2011-2022 走看看