Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

假设有三种重量的砝码,2g、3g、7g,对于任意重量物品,请设计一个函数getResult(weight),接收一个参数weight,返回所需砝码的最小数量。

输入示例:
const weight = 100;

输出示例:
getResult(weight) // 15 其中7g的14个,2g的1个


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
208 views
Welcome To Ask or Share your Answers For Others

1 Answer

动态规划问题:

function getResult (weights, amount) {
    var memo = {};

    function dp (n) {

        if (memo[n]) return memo[n];

        //  base case
        if (n == 0)
            return 0
        if (n < 0)
            return -1
        // # 求最小值,所以初始化为正无穷
        var res = Infinity;
        for (let weight of weights.values()) {
            subproblem = dp(n - weight)
            // # 子问题无解,跳过
            if (subproblem == -1)
                continue
            res = Math.min(res, 1 + subproblem)
        }
        res = res === Infinity ? -1 : res;
        memo[n] = res = res === Infinity ? -1 : res;
        return memo[n];
    }

    return dp(amount)
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...