一道非常经典的面试题目,给你两个鸡蛋,在一幢100层的大楼里面,至少扔几次可以测出让鸡蛋破碎的临界高度?
最朴素的做法是从100层一直扔到1层,不过这样明显不是最优的。这题目其实可以转化为dp求解,假设有n层,你随机选了一层x,如果鸡蛋碎了,那么你只剩一个鸡蛋了,为了确保能够找到临界高度,你不得不从第一层往上一层一层扔剩下的一个鸡蛋。如果没碎呢,你还剩2个鸡蛋,但你已经用了一次测试机会。这时候的次数应该为1+(n-x)层用了两个鸡蛋的最小次数。这里其实是dp的思维了。
假设dp[n]为在n层用两个鸡蛋测出临界高度的最小次数,
dp[n]=min(max(i,1+dp[n−i]))(1≤i≤n)
代码实现
dp[1]=1;
for(int i=2;i<=n;i++){
dp[i]=i;
res[i]=i;
for(int j=1;j<i;j++) {
int now = max(j,1+dp[i-j]);
if(dp[i]>now) res[i]=j,dp[i]=now;
}
}
printf("max times for 100 using two eggs : %d\n",dp[100]);
int p = 100;
int cnt = 0;
while(true){
if(p==1){
printf("%d : now is 1 floor , only need one time\n",++cnt);
break;
}
printf("%d : now is %d high : thorw at %d ,if egg break need %d times,else need %d times\n",++cnt,p,res[p],res[p],1+dp[p-res[p]]);
p = p - res[p];
}
输出
max times for 100 using two eggs : 14
1 : now is 100 high : thorw at 9 ,if egg break need 9 times,else need 14 times
2 : now is 91 high : thorw at 13 ,if egg break need 13 times,else need 13 times
3 : now is 78 high : thorw at 12 ,if egg break need 12 times,else need 12 times
4 : now is 66 high : thorw at 11 ,if egg break need 11 times,else need 11 times
5 : now is 55 high : thorw at 10 ,if egg break need 10 times,else need 10 times
6 : now is 45 high : thorw at 9 ,if egg break need 9 times,else need 9 times
7 : now is 36 high : thorw at 8 ,if egg break need 8 times,else need 8 times
8 : now is 28 high : thorw at 7 ,if egg break need 7 times,else need 7 times
9 : now is 21 high : thorw at 6 ,if egg break need 6 times,else need 6 times
10 : now is 15 high : thorw at 5 ,if egg break need 5 times,else need 5 times
11 : now is 10 high : thorw at 4 ,if egg break need 4 times,else need 4 times
12 : now is 6 high : thorw at 3 ,if egg break need 3 times,else need 3 times
13 : now is 3 high : thorw at 2 ,if egg break need 2 times,else need 2 times
14 : now is 1 floor , only need one time