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

跳水板-面试题 16.11 #118

Open
sl1673495 opened this issue Jul 8, 2020 · 2 comments
Open

跳水板-面试题 16.11 #118

sl1673495 opened this issue Jul 8, 2020 · 2 comments

Comments

@sl1673495
Copy link
Owner

sl1673495 commented Jul 8, 2020

你正在使用一堆木板建造跳水板。有两种类型的木板,其中长度较短的木板长度为 shorter,长度较长的木板长度为 longer。你必须正好使用 k 块木板。编写一个方法,生成跳水板所有可能的长度。

返回的长度需要从小到大排列。

示例:

输入:
shorter = 1
longer = 2
k = 3
输出: {3,4,5,6}
提示:

0 < shorter <= longer
0 <= k <= 100000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/diving-board-lcci
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路

这个排列组合很简单,设 i 是使用短木板的数量,当你用了 ishorter 的话,那么一定只剩下k - ilonger,所以 i[0, k] 的范围里做一次遍历,分别把得到的结果都加到 res 数组里即可。

注意特殊情况:

  • k = 0 直接返回空数组。
  • shorter = longer 的时候,直接返回 [shorter * k]
/**
 * @param {number} shorter
 * @param {number} longer
 * @param {number} k
 * @return {number[]}
 */
let divingBoard = function (shorter, longer, k) {
    if (k === 0) {
        return []
    }
    if (shorter === longer) {
        return [k * shorter]
    }

    let res = []
    for (let i = 0; i <= k; i++) {
        let longCount = i
        let shortCount = k - i
        res.push(shortCount * shorter + longCount * longer)
    }

    return res
};
@Chocolate1999
Copy link

var divingBoard = function(shorter, longer, k) {
    if(k===0) return []
    if(shorter === longer) return [k*shorter]
    let res = []
    for(let i=k;i>=0;i--){
        let shortCnt = i
        let longCnt = k-i
        let cnt = shortCnt*shorter + longCnt*longer
        res.push(cnt)
    }
    return res
};

@faceACG
Copy link

faceACG commented Jun 13, 2023

function divingBoard(shorter,longer,k){
const result = new Set()
for(let i = 0;i<=k;i++){
const item = shorter * i + longer * (k-i);
result.add(item);
}
return [...result]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants