|
| 1 | +/** |
| 2 | + * @param {number[]} coins |
| 3 | + * @param {number} amount |
| 4 | + * @return {number} |
| 5 | + */ |
| 6 | + |
| 7 | +/** |
| 8 | + * combination sum ํ์ด๋ฅผ ํ์ฉํ์ง๋ง amount๊ฐ ์ปค์ |
| 9 | + * time limit exceeded |
| 10 | + * */ |
| 11 | + |
| 12 | +var coinChange = function (coins, amount) { |
| 13 | + let answer = []; |
| 14 | + let coins_desc = coins.reverse(); |
| 15 | + |
| 16 | + if (amount === 0) return 0; |
| 17 | + |
| 18 | + function permute(arr = [], sum = 0, index = 0) { |
| 19 | + if (sum > amount) return; |
| 20 | + // ๊ฐ์ ๊ฒฝ์ฐ์๋ง result์ ๋ด๊ธฐ |
| 21 | + if (sum === amount) { |
| 22 | + if (answer.length === 0) { |
| 23 | + answer = [...arr]; |
| 24 | + } else { |
| 25 | + if (arr.length < answer.length) { |
| 26 | + answer = [...arr]; |
| 27 | + } else { |
| 28 | + return answer.length; |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | + for (let i = index; i < coins.length; i++) { |
| 33 | + // target๋ณด๋ค ํฉ์ด ์์ผ๋ฉด ์ฌ๊ท์ ์ผ๋ก ํด๋น ๊ฐ์ arr์ ๋ฃ๊ณ , sum์ ์ถ๊ฐ |
| 34 | + permute([...arr, coins_desc[i]], sum + coins_desc[i], i); |
| 35 | + } |
| 36 | + } |
| 37 | + permute(); |
| 38 | + return answer.length === 0 ? -1 : answer.length; |
| 39 | +}; |
| 40 | + |
| 41 | +/** |
| 42 | + * ํ์ด(์ฐธ๊ณ ): combination sum์ dp๋ก ํ๋ ค๊ณ ํ์๋๋ฐ, ์ฌ์ค ์ด ๋ฌธ์ ๊ฐ dp๋ก ํ์ด์ผ ํ๋ ๋ฌธ์ |
| 43 | + */ |
| 44 | + |
| 45 | +/** |
| 46 | + * @param {number[]} coins |
| 47 | + * @param {number} amount |
| 48 | + * @return {number} |
| 49 | + */ |
| 50 | +var coinChange = function (coins, amount) { |
| 51 | + let dp = Array.from({ length: amount + 1 }, () => Infinity); |
| 52 | + dp[0] = 0; |
| 53 | + |
| 54 | + for (const coin of coins) { |
| 55 | + for (let i = coin; i <= amount; i += 1) { |
| 56 | + dp[i] = Math.min(dp[i], dp[i - coin] + 1); |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + return dp[amount] === Infinity ? -1 : dp[amount]; |
| 61 | +}; |
0 commit comments