You are given k
identical eggs and you have access to a building with n
floors labeled from 1
to n
.
You know that there exists a floor f
where 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 unbroken egg and drop it from any floor x
(where 1 <= x <= n
). If the egg breaks, you can no longer use it. However, if the egg does not break, you may reuse it in future moves.
Return the minimum number of moves that you need to determine with certainty what the value of f
is.
class Solution:
def superEggDrop(self, k: int, n: int) -> int:
dp = [[0 for _ in range(n+1)] for i in range(k+1)]
dp[1][1] = 1
# dp[i][j] 表示为:一共有 i 个鸡蛋,最多扔 j 次鸡蛋(碎没碎都算 1 次)的条件下,
# 最多可以检测的楼层个数(逆向思维)
for i in range(1, k+1):
for j in range(1, n+1):
# dp[i][j-1]:鸡蛋没碎的情况 dp[i-1][j-1]:鸡蛋碎了的情况 1:正在检测的这一层
dp[i][j] = dp[i][j-1] + dp[i-1][j-1] + 1
# 因为j本来就是按循序遍历的,所以找到的一定是最小的j
# i == k: k次机会用完,dp[i][j] >= n: 能检测的层数大于等于需要检测的层数
if i == k and dp[i][j] >= n:
return j
return n #最多每层楼扔一次