vivo21届笔试题:手机跌落测试(与力扣的887. 鸡蛋掉落相同)

1、题目描述:
此题与力扣的887. 鸡蛋掉落相同
vivo21届笔试题:手机跌落测试(与力扣的887. 鸡蛋掉落相同)_第1张图片
vivo21届笔试题:手机跌落测试(与力扣的887. 鸡蛋掉落相同)_第2张图片
2、题解:
动态规划
打表法(超时)

class Solution:
    def superEggDrop(self, K: int, N: int) -> int:

        dp = [[i for j in range(K + 1)] for i in range(N + 1)]

        for j in range(K + 1):
            dp[0][j] = 0

        dp[1][0] = 0
        for j in range(1,K + 1):
            dp[1][j] = 1

        for i in range(N + 1):
            dp[i][0] = 0
            dp[i][1] = i

        for i in range(2, N + 1):
            for j in range(2, K + 1):
                for k in range(1, i + 1):
                    # 把最后一行,最后一列的求解过程制作成图表
                    dp[i][j] = min(dp[i][j], max(dp[k - 1][j - 1], dp[i - k][j]) + 1)
        return dp[N][K]

方法2:递归+二分查找

class Solution:
    def superEggDrop(self, K: int, N: int) -> int:
        memo = {}
        def dp(k,n):
            if (k,n) not in memo:
                if n == 0:
                    ans = 0
                elif k == 1:
                    ans = n
                else:
                    low,high = 1,n 
                    while low + 1 < high:
                        mid = low + (high - low) // 2
                        t1 = dp(k-1,mid-1)
                        t2 = dp(k,n - mid)
                        if t1 < t2:
                            low = mid 
                        elif t1 > t2:
                            high = mid 
                        else:
                            low = high = mid 
                    ans = 1 + min(max(dp(k-1,x-1),dp(k,n-x)) for x in (low,high))
                memo[k,n] = ans
            return memo[k,n]
        return dp(K,N)

你可能感兴趣的:(面试题)