[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 }
相關文章
相關標籤/搜索