Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

887. 鸡蛋掉落 #58

Open
webVueBlog opened this issue Sep 12, 2022 · 0 comments
Open

887. 鸡蛋掉落 #58

webVueBlog opened this issue Sep 12, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

webVueBlog commented Sep 12, 2022

887. 鸡蛋掉落

Description

Difficulty: 困难

Related Topics: 数学, 二分查找, 动态规划

给你 k 枚相同的鸡蛋,并可以使用一栋从第 1 层到第 n 层共有 n 层楼的建筑。

已知存在楼层 f ,满足 0 <= f <= n ,任何从 高于 f 的楼层落下的鸡蛋都会碎,从 f 楼层或比它低的楼层落下的鸡蛋都不会破。

每次操作,你可以取一枚没有碎的鸡蛋并把它从任一楼层 x 扔下(满足 1 <= x <= n)。如果鸡蛋碎了,你就不能再次使用它。如果某枚鸡蛋扔下后没有摔碎,则可以在之后的操作中 重复使用 这枚鸡蛋。

请你计算并返回要确定 f 确切的值最小操作次数 是多少?

示例 1:

输入:k = 1, n = 2
输出:2
解释:
鸡蛋从 1 楼掉落。如果它碎了,肯定能得出 f = 0 。 
否则,鸡蛋从 2 楼掉落。如果它碎了,肯定能得出 f = 1 。 
如果它没碎,那么肯定能得出 f = 2 。 
因此,在最坏的情况下我们需要移动 2 次以确定 f 是多少。 

示例 2:

输入:k = 2, n = 6
输出:3

示例 3:

输入:k = 3, n = 14
输出:4

提示:

  • 1 <= k <= 100
  • 1 <= n <= 104

Solution

Language: JavaScript

/**
 * @param {number} k
 * @param {number} n
 * @return {number}
 */

var superEggDrop = function(k, n) {
    // 二维数组 [k+1] 行 [n+1]列 初始化为0
    const dp = new Array(k+1).fill(0).map(() => new Array(n+1).fill(0))

    let m = 0
    while (dp[k][m] < n) {
        m++
        for (let i = 1; i <= k; i++) {
            dp[i][m] = dp[i][m-1] + dp[i-1][m-1] + 1
        }
    }
    return m
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant