蛋滴拼图中的递归

时间:2018-08-08 00:59:06

标签: algorithm recursion dynamic

n个鸡蛋和n层楼的鸡蛋。编写算法以查找所需的最小滴数,以了解如果将鸡蛋从地板上掉下来,鸡蛋将掉落。

我的解决方案是将地板分成大小为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,因为它会给出 k个低于x的楼层不是精确地位于x上方的楼层
例如,在x = 6
eggDrop(10, 2) = 1 + min{max(eggDrop(2 - 1, 6 - 1), eggDrop(2, 9 - 6))
给,
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/

2 个答案:

答案 0 :(得分:1)

那几层楼没关系。重要的是我们需要考虑的楼层数。如果我们有9层,并且鸡蛋在第6层幸存,那么我们需要考虑6之上的3层:第7、8和9层。另一种思考的方法是,必须测试7-9楼与测试1-3楼完全相同(就最坏情况而言,跌落次数而言)。

答案 1 :(得分:1)

那么,六楼以上有几层?那将是3(7、8、9楼)。如果您想弄清楚是哪一个罪魁祸首,这些楼层有多高无关紧要。

让我画一个不同的例子供您参考。假设您正在尝试通过排序列表进行二进制搜索,只是为了查看元素是否存在。

示例列表:gsub!

假设您要搜索3。第一步是查看中间元素values = [0, 1, 2, 3, 4]并将其与3进行比较。由于3大于v[2],因此您应该递归在子数组v[2] = 2上调用binarySearch(a1)

递归调用中会发生什么?此时,它基本上是一个基本情况,因此可以看一下v[3 - 4]。比较有效,因此您返回a1[0] = 3

在此示例中,在子数组TRUE上调用binarySearch与调用v[3 - 4]相同。当您引用eggDrop(2, 3)时,您实际上是在引用a1[0]。同样,对v[3]的递归调用中的第1层实际上引用了父调用中的第7层。索引“重置”,但它们实际上引用相同的值。