动态规划法最少硬币找零问题记录

function minCoinChange(coins, amount) {
    const cache = {}

    const makeChange = (value) => {
        //若amount <= 0 返回空数组
        if (!value) {
            return []
        }
        //缓存中存在直接返回
        if (cache[value]) {
            return cache[value]
        }

        let min = []
        let newMin
        let newAmount

        for (let i = 0; i < coins.length; i++) {

            const coin = coins[i]

            newAmount = value - coin
            //传入0会返回空数组 所以这里>=0
            if (newAmount >= 0) {
                newMin = makeChange(newAmount)
            }

            if (newAmount >= 0 &&
                //因为newMin需要加上coin然后小于min
                //newMIn + 1 < min
                //newMin < min - 1
                (newMin.length < min.length - 1 || !min.length)

                && (newMin.length || newAmount)) {

                min = [coin].concat(newMin)

            }
        }

        return (cache[value] = min)
    }

    return makeChange(amount)
}


console.log(minCoinChange([1, 5, 10, 25], 1));
// 1 []

上一篇:java读写条形码、二维码


下一篇:全面理解Python中的类型提示(Type Hints)