/** * @param {number[]} coins * @param {number} amount * @return {number} */ const coinChange = (coins, amount) => { if (!coins) { return -1; } return getCoinChangeMin(coins, amount, {}); }; const getCoinChangeMin = (coins, amount, dp) => { if (amount < 0) { return -1; } if (amount === 0) { return 0; } if (amount in dp) { return dp[amount]; } let min = Number.MAX_VALUE; for (const coin of coins) { let currMin = getCoinChangeMin(coins, amount - coin, dp); if (currMin >= 0 && currMin < min) { min = currMin; } } return dp[amount] = min === Number.MAX_VALUE ? -1 : min + 1; };
Categories