★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公众号:山青咏芝(shanqingyongzhi)
➤博客园地址:山青咏芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址: http://www.javashuo.com/article/p-befuflir-me.html
➤若是连接不是山青咏芝的博客园地址,则多是爬取做者的文章。
➤原文已修改更新!强烈建议点击原文地址阅读!支持做者!支持原创!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
You are given K
eggs, and you have access to a building with N
floors from 1
to N
. git
Each egg is identical in function, and if an egg breaks, you cannot drop it again.github
You know that there exists a floor F
with 0 <= F <= N
such that any egg dropped at a floor higher than F
will break, and any egg dropped at or below floor F
will not break.微信
Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X
(with 1 <= X <= N
). less
Your goal is to know with certainty what the value of F
is.ide
What is the minimum number of moves that you need to know with certainty what F
is, regardless of the initial value of F
? ui
Example 1:spa
Input: K = 1, N = 2 Output: 2 Explanation: Drop the egg from floor 1. If it breaks, we know with certainty that F = 0. Otherwise, drop the egg from floor 2. If it breaks, we know with certainty that F = 1. If it didn't break, then we know with certainty F = 2. Hence, we needed 2 moves in the worst case to know what F is with certainty.
Example 2:code
Input: K = 2, N = 6
Output: 3
Example 3:htm
Input: K = 3, N = 14 Output: 4
Note:
1 <= K <= 100
1 <= N <= 10000
你将得到 K
个鸡蛋,并可使用一栋从 1
到 N
共有 N
层楼的建筑。
每一个蛋的功能都是同样的,若是一个蛋碎了,你就不能再把它掉下去。
你知道存在楼层 F
,知足 0 <= F <= N
任何从高于 F
的楼层落下的鸡蛋都会碎,从 F
楼层或比它低的楼层落下的鸡蛋都不会破。
每次移动,你能够取一个鸡蛋(若是你有完整的鸡蛋)并把它从任一楼层 X
扔下(知足 1 <= X <= N
)。
你的目标是确切地知道 F
的值是多少。
不管 F
的初始值如何,你肯定 F
的值的最小移动次数是多少?
示例 1:
输入:K = 1, N = 2 输出:2 解释: 鸡蛋从 1 楼掉落。若是它碎了,咱们确定知道 F = 0 。 不然,鸡蛋从 2 楼掉落。若是它碎了,咱们确定知道 F = 1 。 若是它没碎,那么咱们确定知道 F = 2 。 所以,在最坏的状况下咱们须要移动 2 次以肯定 F 是多少。
示例 2:
输入:K = 2, N = 6 输出:3
示例 3:
输入:K = 3, N = 14 输出:4
提示:
1 <= K <= 100
1 <= N <= 10000
1 class Solution { 2 func superEggDrop(_ K: Int, _ N: Int) -> Int { 3 var dp:[[Int]] = [[Int]](repeating:[Int](repeating:0,count:K + 1),count:N + 1) 4 var m:Int = 0 5 while(dp[m][K] < N) 6 { 7 m += 1 8 for k in 1...K 9 { 10 dp[m][k] = dp[m - 1][k - 1] + dp[m - 1][k] + 1 11 } 12 } 13 return m 14 } 15 }
1 class Solution { 2 var mark = [String : Int]() 3 func superEggDrop(_ K: Int, _ N: Int) -> Int { 4 var step = 1 5 while reachHeight(K, step) < N { 6 step += 1 7 } 8 return step 9 } 10 11 func reachHeight(_ K: Int, _ N: Int) -> Int { 12 let key = "\(K),\(N)" 13 if let result = mark[key] { 14 return result 15 } 16 if K == 0 || N == 0 { 17 return 0 18 } 19 if K == 1 || N == 1 { 20 return N 21 } 22 var height = N 23 for i in 1..<N { 24 height += reachHeight(K - 1, i) 25 } 26 mark[key] = height 27 return height 28 } 29 }