[Swift]LeetCode375. 猜数字大小 II | Guess Number Higher or Lower II

原文地址:http://www.javashuo.com/article/p-mfyhhdqa-dr.html html

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

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

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

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.blog

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.get


咱们正在玩一个猜数游戏,游戏规则以下:it

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

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

然而,当你猜了数字 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 }
相关文章
相关标签/搜索