【发布时间】:2019-01-15 03:54:04
【问题描述】:
有 n 个鸡蛋和有 k 层的建筑物。编写一个算法,找出最小的掉落次数,以便知道如果鸡蛋从哪个楼层掉下来,鸡蛋会破裂。
我的解决方案是将地板分成几组大小为 sqrt(k) 的块。例如,如果 k =100,我将检查鸡蛋是否会从 10、20、30....100 楼破裂,然后在该块中进行线性搜索。解决方案将是 O(sqrt(k))。
现在,我看到的动态编程解决方案是:
When we drop an egg from a floor x, there can be two cases (1) The egg breaks (2) The egg doesn’t break.
1) If the egg breaks after dropping from xth floor, then we only need to check for floors lower than x with remaining eggs; so the problem reduces to x-1 floors and n-1 eggs
2) If the egg doesn’t break after dropping from the xth floor, then we only need to check for floors higher than x; so the problem reduces to k-x floors and n eggs.
Since we need to minimize the number of trials in worst case, we take the maximum of two cases. We consider the max of above two cases for every floor and choose the floor which yields minimum number of trials.
k ==> Number of floors
n ==> Number of Eggs
eggDrop(n, k) ==> Minimum number of trials needed to find the critical
floor in worst case.
eggDrop(n, k) = 1 + min{max(eggDrop(n - 1, x - 1), eggDrop(n, k - x)):
x is floors in {1, 2, ..., k}}
我不知道我们为什么要使用 eggDrop(n, k - x) 来计算 Floor above x with k-x,因为它会给出 x 下方的 k 层 而 X 上方的楼层不准确?
例如,在 x = 6eggDrop(10, 2) = 1 + min{max(eggDrop(2 - 1, 6 - 1), eggDrop(2, 9 - 6))
Gives,eggDrop(10, 2) = 1 + min{max(eggDrop(1, 5), eggDrop(2, 3))
eggDrop(2, 3)) 基本上是一栋有 3 层和 2 个鸡蛋的建筑物,而不是 6 楼以上的楼层。
谢谢!
来源:https://www.geeksforgeeks.org/dynamic-programming-set-11-egg-dropping-puzzle/
【问题讨论】:
标签: algorithm recursion dynamic