【问题标题】:Recursion in Egg Drop PuzzleEgg Drop 谜题中的递归
【发布时间】: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 = 6
eggDrop(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


【解决方案1】:

这些楼层是什么并不重要。重要的是我们需要考虑的楼层数。如果我们有 9 层,一个鸡蛋在 6 层存活,我们需要考虑 6 层以上的 3 层:第 7 层、第 8 层和第 9 层。另一种思考方式是,必须测试 7-9 层与测试 1-3 层完全相同(就最坏情况下的掉落次数而言)。

【讨论】:

  • @Kartik 我不是指测试的实际结果。如果您已经知道所需的楼层是 7 到 9 层,那么这与您知道鸡蛋会在 1 到 3 层破裂的问题本质上是一样的。请记住,我们只关心这里最坏的情况。
【解决方案2】:

嗯,6楼以上有多少层?那将是 3(7、8、9 楼)。如果您想找出罪魁祸首,这些楼层有多高并不重要。

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

示例列表:values = [0, 1, 2, 3, 4]

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

递归调用会发生什么?在这一点上,它基本上是一个基本情况,所以它可能看a1[0] = 3。比较有效,因此您返回 TRUE

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

【讨论】:

    猜你喜欢
    • 2015-07-03
    • 2020-05-05
    • 2018-05-18
    • 2022-01-15
    • 2016-05-25
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 2019-02-06
    相关资源
    最近更新 更多