891. Super Egg Drop
You are given K
eggs, and you have access to a building with N
floors from 1
to N
.
Each egg is identical in function, and if an egg breaks, you cannot drop it again.
You know that there exists a floor F
with 0 <= F <= N
such that any egg dropped at a floor higher than F
will break, and any egg dropped at or below floor F
will not break.
Each move, you may take an egg (if you have an unbroken one) and drop it from any floor X
(with 1 <= X <= N
).
Your goal is to know with certainty what the value of F
is.
What is the minimum number of moves that you need to know with certainty what F
is, regardless of the initial value of F
?
Example 1:
Input: K = 1, N = 2 Output: 2 Explanation: Drop the egg from floor 1. If it breaks, we know with certainty that F = 0. Otherwise, drop the egg from floor 2. If it breaks, we know with certainty that F = 1. If it didn't break, then we know with certainty F = 2. Hence, we needed 2 moves in the worst case to know what F is with certainty.
K个鸡蛋,N层楼,在最坏的情况下,扔多少次才能够准确测试出哪层楼开始往下扔,鸡蛋会碎。
1、考虑1个鸡蛋的情况,所以必须从1楼开始扔到N楼,需要N次。 total(x, 1) = x
2、考虑2个鸡蛋,假设最少需要x次才能测出。
我们假设第一个鸡蛋在t楼往下扔,破了,所以剩下的t-1楼需要另外一个鸡蛋一层层测试,所以需要t-1次。那么就有 1 + t - 1 = x,t = x。
如果没有破,我们假设第一个鸡蛋第二次在x + t的处往下扔,破了,所以第二个鸡蛋只剩x - 2次测试机会,所以t = x - 1
同理,后面有 t = x - 2, x - 3 ... 1
那么就有 x + x - 1 + x - 2 + ... + 1 = x(x + 1) / 2 层楼被测试, total(x, 2) = 1 + total(x - 1, 1) + 1 + total(x - 2, 1) + ... + 1 + total(1, 1) + 1 + total(0, 1) = x(x + 1) / 2 >= N
3、考虑有3个鸡蛋,同2中思想,假设第一个鸡蛋在t1破碎,那么剩余的两个鸡蛋要在x - 1次机会中测试完t1 - 1层,所以有 1 + (x - 1)(x) / 2 = t1
假设第一个鸡蛋在t1 + t2破碎,那么剩余的两个鸡蛋要在x - 2次机会中测试完t2 - 1层,所以有 1 + (x - 2)(x - 1) / 2 = t2
那么就有 total(x, 3) = 1 + total(x - 1, 2) + ... + 1 + total(1, 2) = 1 + (x - 1)(x) / 2 + 1 + (x - 2)(x - 1) / 2 + ... + 1 >= N
4、假设有K个鸡蛋,同理递归推公式
total(x, K) = 1 + total(x - 1, K - 1) + 1 + total(x - 2, K - 1) + ... + 1 + total(1, K - 1) >= N
所以这道题就转化为求x, 使得 total(x, K) >= N
1 class Solution { 2 public: 3 int total(int num, int k) { 4 if (k == 1) 5 return num; 6 int sum = 0; 7 while (num) 8 sum += 1 + total(--num, k - 1); 9 return sum; 10 } 11 int superEggDrop(int K, int N) { 12 for (int i = 1; i <= N; ++i) { 13 if(total(i, K) >= N) { 14 return i; 15 } 16 } 17 } 18 };
改进:用dp计算total,递推公式:total(x, k) = total(x - 1, k) + total(x - 1, k - 1) + 1
class Solution { public: int total(int num, int k) { vector<vector<int>> dp(k, vector<int>(num, 1)); for (int i = 0; i < num; ++i) dp[0][i] = i + 1; for (int i = 1; i < k; ++i) for (int j = 1; j < num; ++j) dp[i][j] = dp[i - 1][j - 1] + dp[i][j - 1] + 1; return dp[k - 1][num - 1]; } int superEggDrop(int K, int N) { for (int i = 1; i <= N; ++i) { if(total(i, K) >= N) { return i; } } } };
经过测试不建议把main函数里面的total也挪进去用dp算,因为实际上当N和K都很大时,往往最后的n << N,这样子开一个N * K的数组就消耗很大。
如果放进去的话,先遍历K会比先遍历N更快,理由同上。