leetcode-887-线性DP-鸡蛋掉落

题目

1.png

解法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// 二分查找+动态规划
class Solution {
unordered_map<int, int> memo;
int dp(int K, int N) {
if (memo.find(N * 100 + K) == memo.end()) {
int ans;
if (N == 0) ans = 0;
else if (K == 1) ans = N;
else {
int lo = 1, hi = N;
while (lo + 1 < hi) {
int x = (lo + hi) / 2;
int t1 = dp(K-1, x-1);
int t2 = dp(K, N-x);

if (t1 < t2) lo = x;
else if (t1 > t2) hi = x;
else lo = hi = x;
}

ans = 1 + min(max(dp(K-1, lo-1), dp(K, N-lo)),
max(dp(K-1, hi-1), dp(K, N-hi)));
}

memo[N * 100 + K] = ans;
}

return memo[N * 100 + K];
}
public:
int superEggDrop(int K, int N) {
return dp(K, N);
}
};

参考

鸡蛋掉落