两道经典算法题(扔鸡蛋&猜大小2)有异曲同工之妙

160 阅读1分钟

887. 鸡蛋掉落

  • 此题逆向思维比较好解答
  • 题目问的是N 个楼层,有 K 个蛋,求最少要扔 T 次,才能保证当 F 无论是 0 <= F <= N 中哪个值,都能测试出来
  • 转化为有 K 个蛋,扔 T 次,求可以确定 F 的个数,然后得出 N 个楼层
class Solution {
    public int superEggDrop(int k, int n) {
        int t=1;
        while(calF(k,t)<n+1)t++;
        return t;
    }
    private int  calF(int k,int t){
        //**机会为1或者蛋为1时,只能一层一层去尝试**
        if(t==1||k==1)return t+1;
        return calF(k-1,t-1)+calF(k,t-1);
    }
}

参考leetcode-cn.com/problems/su…

375. 猜数字大小 II

class Solution {
    public int getMoneyAmount(int n) {
        int[][] dp=new int[n+1][n+1];
       return dfs(dp,1,n);
       
    }
    int dfs(int[][] dp,int left,int right){
        if(left>=right) return 0;
        if(dp[left][right]!=0)return dp[left][right];
        int ans=Integer.MAX_VALUE;
        for(int i=left;i<=right;i++){
            int cost=i+Math.max(dfs(dp,left,i-1),dfs(dp,i+1,right));
            ans=Math.min(ans,cost);
        }
        dp[left][right]=ans;
        return ans;
    }
}