254. Drop Eggs (扔鸡蛋经典题)

  1. Drop Eggs
    中文English
    There is a building of n floors. If an egg drops from the k th floor or above, it will break. If it’s dropped from any floor below, it will not break.

You’re given two eggs, Find k while minimize the number of drops for the worst case. Return the number of drops in the worst case.

Example
Example 1:

Input: 100
Output: 14
Example 2:

Input: 10
Output: 4
Clarification
For n = 10, a naive way to find k is drop egg from 1st floor, 2nd floor … kth floor. But in this worst case (k = 10), you have to drop 10 times.

Notice that you have two eggs, so you can drop at 4th, 7th & 9th floor, in the worst case (for example, k = 9) you have to drop 4 times.

解法1:
具体思路参见
https://segmentfault.com/a/1190000016364846
解方程: x + (x-1) + (x-2) + … + 1 >= n, 即求解x^2+x-2n>=0的解。
注意:

  1. 当n很大时,要用long long
  2. 用ceil函数,当结果是2时返回2,结果是2.1到2.9都返回3。
    代码如下:
class Solution {
public:
    /**
     * @param n: An integer
     * @return: The sum of a and b
     */
    int dropEggs(int n) {
        if (n <= 2) return n;
        return ceil((-1 + sqrt((long long)n * 8 + 1)) / 2);
    }
};

解法2:DP
下面这个链接讲的不错
https://zhuanlan.zhihu.com/p/41257286
思路:
DP[i][j]表示用i个鸡蛋,j层楼的情况下最坏情况下所需扔鸡蛋的最少数目。
可知初始条件为:
DP[1][0] = 0; DP[2][0] = 0;
DP[1][1] = 1; DP[2][1] = 1;
DP[1][i] = i; //i = 1 … n
对于DP[2][i], i = 2 … n的情况,我们可以这样考虑:
遍历j=2…i,求DP[2][j],分两种情况:
如果第1个鸡蛋在第j-1层摔破了,则我们在第j层只需摔第2个鸡蛋一次即可,此时总摔鸡蛋数为DP[1][j-1]+1。
注意上面的1是因为第j层需要摔第2个鸡蛋1次。为什么DP[1][j-1]不能写成1呢?因为第1个鸡蛋在第j-1层摔破了,我们不能肯定在第1,2,…,j-2层不会破,所以要用DP[1][j-1]。
如果第1个鸡蛋在第j-1层没有摔破,则我们在第j到i层有2个鸡蛋可以摔,此时退化到DP[2][i-j]的情况。该种情形下总共扔1+DP[2][i-j]。那个1就是表示第1个鸡蛋在第j-1层扔了1次。这里我们为什么只考虑用1,而不用考虑DP[1][j-1]呢?因为如果第j-1层没有摔破,第1,2,…,j-2层也就不用考虑了。
因为是求最坏情况下的数目,所以DP[2][j]=1 + max(DP[1][j-1]+1, DP[2][i-j])。
而我们是要求所有最坏情况下的最少数目,所以DP[2][j]=min(1 + max(DP[1][j-1]+1, DP[2][i-j]))。i = 2…n, j = 2…i。

代码如下:

class Solution {
public:
    /**
     * @param n: An integer
     * @return: The sum of a and b
     */
    int dropEggs(int n) {
        if (n <= 1) return n;
        
        vector<vector<int>> DP(3, vector<int>(n + 1, INT_MAX));
        
        DP[1][0] = 0; DP[2][0] = 0;
        DP[1][1] = 1; DP[2][1] = 1;
        
        for (int i = 1; i <= n; ++i) {
            DP[1][i] = i;
        }
        
        for (int i = 2; i <= n; ++i) {
            for (int j = 2; j <= i; ++j) {
                DP[2][i] = min(DP[2][i], 1 + max(DP[1][j - 1], DP[2][i - j]));   
            }
             
        }
        
        return DP[2][n];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值