经典动态规划,lintcode上通过69% ,复杂度高,对于大数无法通过
时间复杂度:O(mn^2); m为鸡蛋数,n为楼层数
空间复杂度:O(mn)
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
//鸡蛋数为2个
int dropEggs(int n) {
if(n <= 0)
return -1;
int **dp = new int *[3];//n层楼,两个鸡蛋,生成3*(n+1)数组
for(int i = 0;i < 3; i ++){
dp[i] = new int[n + 1];
}
//楼层小于1时,则可初始化为0或者1
for(int i = 1; i < 3; i ++){
dp[i][0] = 0;
dp[i][1] = 1;
}
//只有一个鸡蛋时,必须尝试n次(即有多少层楼,最多尝试次数为多少次)
for(int j = 1; j < n + 1; j ++){
dp[1][j] = j;
}
for(int i = 2; i < 3; i ++){//鸡蛋数
for(int j = 2; j <= n; j ++){//楼层数
dp[i][j] = INT_MAX;
for(int k = 1; k <= j; k ++){
int res = dp[i - 1][k - 1] > dp[i][j - k] ? (1 + dp[i - 1][k - 1]) : (1 + dp[i][j - k]);
if(res < dp[i][j])
dp[i][j] = res;
}
}
}
return dp[2][n];
}
int main(){
cout<<dropEggs(10000007)<<endl;
return 0;
}
递归法:大数始终无法通过
class Solution {
public:
int dropEggs(int floors) {
int times = 1;
while(DroppingMax(2, times) < floors){
++times;
}
return times;
}
int DroppingMax( int eggs, int times){
if(eggs == 1){
return times;
}
if(eggs >= times){
return (int)pow(2, times) - 1;
}
return DroppingMax(eggs, times -1) + DroppingMax(eggs -1, times - 1) + 1;
}
};
公式法:解方程x*(x+1)/2 = n,大数可通过
测试用例:2147483647
输出:65536
#include<iostream>
using namespace std;
class Solution {
public:
int dropEggs(int floors) {
if(floors == 0 || floors == 1)
return floors;
long long i = 1;
while(i){
if(i * (i + 1) / 2 >= floors)
return i;
i ++;
}
}
};
int main(){
Solution s;
cout<<s.dropEggs(2147483647)<<endl;
return 0;
}